Answer the question
In order to leave comments, you need to log in
How to pass a POST array using Ajax where input has the same name?
There is a form where there are text inputs with different names and inputs that appear dynamically with the same name.
The problem is that when an array is formed for POST via AJAX, only the last value of the field where the name is the same gets into the array:
The form fields are like this:
<form name="zayavka" method="post" enctype="multipart/form-data">
<input type="text" name="FIO" placeholder="Иван">
<input type="text" name="GOROD" placeholder="Москва">
<input id="file-doc308" type="hidden" name="FOTO[]" value="308">
<input id="file-doc309" type="hidden" name="FOTO[]" value="309">
<input id="file-doc310" type="hidden" name="FOTO[]" value="310">
<div id="error"></div>
<button class="btn btn-primary" type="submit">Отправить</button>
</form>
$('form[name=zayavka]').submit(function () {
var o = new Object();
$(this).find('input, textarea').each(function () {
o[$(this).attr('name')] = $(this).val();
});
$.post('/bitrix/templates/site/js/form.php', o,
function (data) {
if (data == '1') {
document.getElementById("error").innerHTML = "Спасибо за Вашу заявку! Она направлена на модерацию.";
$('.md-close').click();
}
else document.getElementById("error").innerHTML = "Произошла ошибка! Повторите попытку позже.";
});
//}
return false;
});
o[$(this).attr('name')] = $(this).val();
Array
(
[FIO] =>
[GOROD] =>
[P30] => Array
(
[0] => 310
)
)
Answer the question
In order to leave comments, you need to log in
It turned out to be done.
Since we have a unique ID, we did it as follows:
We catch all inputs with the same name and assign them unique values:
var o = new Object();
$(this).find('input, textarea').each(function () {
if ($(this).attr('name') == 'FOTO[]') {
o['PASSPORT_'+$(this).attr('id')] = $(this).val();
}
else {
o[$(this).attr('name')] = $(this).val();
}
});
$result = [];
$i = 0;
foreach($_POST as $k => $v){
if(preg_match("/^PASSPORT_file-doc\d+$/", $k)){
$result[$i] = $v;
$i++;
}
}
$_POST['FOTO'] = $result;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question