R
R
Roman12902020-07-22 23:07:39
AJAX
Roman1290, 2020-07-22 23:07:39

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>


Ajax data transfer script is like this:
$('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;
  });


As I understand it, the problem is in this line: Apparently, data with the same name="FOTO[]" is being replaced with each other, instead of collecting them in an array. The array is output like this, where only the last file is specified:
o[$(this).attr('name')] = $(this).val();

Array
(
    [FIO] => 
    [GOROD] => 
    [P30] => Array
        (
            [0] => 310
        )

)


Tell me, please, who understands AJAX, how to properly process fields with the same name, so that an array is formed in the post, and only the last file is not taken. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman1290, 2020-07-23
@Roman1290

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();
   }
  });

And then we combine this data into an array by mask, sorting through our $_POST in the php file:
$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 question

Ask a Question

731 491 924 answers to any question