A
A
Alexander Ivanov2021-04-09 15:12:16
AJAX
Alexander Ivanov, 2021-04-09 15:12:16

How to send an array via ajax?

there is an array, two-dimensional

var obj = {
                         'generalFields':{
                             'title':$('input#title').val(),
                             'keywords':$('input#keywords').val(),
                             'mainCategory':$('select#mainCategory').val(),
                             'subCategory':subCategory,
                             'typeCategory':$('select#selecttypeCategory').val(),
                             'description': $('input#description').val(),
                             'comments':$('input[name="comments"]:checked').val(),
                             'fulltext': $('div[role="textbox"]').text(),
                             'imgs':imgs
                         },
                         'optionFields':$('[field=fieldsAdvert]')
                     }

when submitting ajax
$.ajax({                             
                url: '/NewAdvert',
                type:'post',
                contentType: false,
                processData: false,
                data: {data: obj},
                dataType: 'json',
                cache: false,
                success: function (result) {}
            });

an object is sent, when outputting to the print_r($_POST) server, an empty array is displayed

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vItalIyIrtlach, 2021-04-09
@w13vitaliy

Try :

fetch("/your url", {
method: "POST",
body: JSON.stringify({data: obj})
})

N
Nadim Zakirov, 2021-04-09
@zkrvndm

Try my version:

// Функция для преобразования объекта
// в строку формата x-www-form-urlencoded:

function httpBuildQuery(object_to_convert) {
  
  var params = new URLSearchParams();
  
  var paramsGenerator = function(parent_key, iterate_object) {
    
    for (var current_key in iterate_object) {
      
      if (typeof iterate_object[current_key] == 'string' || typeof iterate_object[current_key] == 'number') {
        
        if (parent_key.length > 0) {
          var property_path = parent_key + '[' + current_key + ']';
        } else {
          var property_path = current_key;
        }
        
        params.append(property_path, iterate_object[current_key]);
        
      } else if (typeof iterate_object[current_key] == 'object') {
        
        if (parent_key.length > 0) {
          var property_path = parent_key + '[' + current_key + ']';
        } else {
          var property_path = current_key;
        }
        
        paramsGenerator(property_path, iterate_object[current_key]);
        
      }
      
    }
    
  }
  
  paramsGenerator('', object_to_convert);
  
  return params.toString();
  
}

// Протестируем работу функции на примере:

var test_object = {
  'raz' : 'Первое свойство',
  'dva' : 'Второе свойство',
  'tri' : {
    'test' : 'Тест',
    'proverka' : 'Проверка',
    'massiv' : [
      'aaa',
      'bbb',
      'ccc',
      {
        'lalala' : 'lololo',
        'tratata' : 'trototo'
      },
      123,
      345,
      567
    ]
  }
};

var send_string = httpBuildQuery(test_object);

var response = await (await fetch('/NewAdvert', {
  method: 'POST',
  headers: {
    'Content-Type' : 'application/x-www-form-urlencoded'
  },
  body: send_string
})).text();

console.log(response);

Paste this into the console.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question