Send multidimensional array from JQuery AJAX to PHP

I want to send a multidimensional array to PHP from JQuery AJAX, but it gets to PHP like this

Array
(
[recordid] => 38
[locations] => [object Object],[object Object]
)

      

I must be making some stupid mistake. here is the code. it gets records from the table and sends to PHP

$(document).on('click','.savenow',function(){
    recordid = $(this).data('id');

    locations = [];

    $('.selectrec').each(function () {
        parent = $(this).parent().parent();

        name    = parent.find('td').eq(5);
        address = parent.find('td').eq(6);
        lat     = parent.find('td').eq(1);
        lng     = parent.find('td').eq(2);

        row = [name,address,lat,lng];

        locations.push(row);
    });

    locations = locations.toString();
    $.ajax({
        type: "POST",
        url:'/record/saveSearchedLocations',
        data: { recordid: recordid,locations:locations },
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        error:function(data){
          alert("something went wrong, please try again.");
        }
    });

});

      

and this is the PHP function where I am getting the data:

function saveSearchedLocations(){
    print_r($_POST);
}

      

+3


source to share


4 answers


Use JSON.stringify()

instead toString()

like this:

Change your AJAX call to the following:



$(document).on('click','.savenow',function(){
    recordid = $(this).data('id');

    locations = [];

    $('.selectrec').each(function () {
        parent = $(this).parent().parent();

        name    = parent.find('td').eq(5);
        address = parent.find('td').eq(6);
        lat     = parent.find('td').eq(1);
        lng     = parent.find('td').eq(2);

        row = [name,address,lat,lng];

        locations.push(row);
    });

    ajaxData = { recordid : recordid,locations : locations }
    $.ajax({
        type: "POST",
        url:'/record/saveSearchedLocations',
        data: JSON.stringify(ajaxData),
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        error:function(data){
          alert("something went wrong, please try again.");
        }
    });

});

      

JSON.stringify()

converts your array to an actual json string, not Array.prototype.toString()

which concatenates your array (one level) using a comma as separator.

+4


source


Take this answer as a reference:

I think you need to use JSON.stringify(selectedData)

in order to use it on the server.

jQuery:

var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);

$.post('serive.php', { DTO: JSON.stringify(selectedData) }, 
function(data){ /* handle response,  */ });

      




service.php:

header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');

$foo = json_decode($_POST['DTO']);


$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data

echo json_encode($arr);

      

This should get you started. In response, ajax alert(data.a)

will warn "1"

+1


source


sendAjax = function() {
      var data = {

             foo: 123,
             bar: 456,
             rows: [{
                 column1: 'hello',
                 column2: 'hola',
                 column3: 'bonjour',
             }, {
                 column1: 'goodbye',
                 column2: 'hasta luego',
                 column3: 'au revoir',
             }, ],
             test1: {
                 test2: {
                     test3: 'baz'
                 }
             }
         };

         $.ajax({
             type: 'post',
             cache: false,
             url: './ajax/',
             data: data
         });
     }

      

When the button is clicked, the following structured data is displayed in the PHP $ _POST variable:

Array
    (
        [foo] => 123[bar] => 456[rows] => Array(
            [0] => Array(
                [column1] => hello[column2] => hola[column3] => bonjour
            )

            [1] => Array(
                [column1] => goodbye[column2] => hasta luego[column3] => au revoir
            )

        )

        [test1] => Array(
            [test2] => Array(
                [test3] => baz
            )

        )

    )

      

This will only work with jQuery 1.4.0+. Otherwise, jQuery simply calls .toString () on the nested array on key "strings" and the nested object on key "test1", and they are passed to PHP with useless values ​​"[object Object

here is the link you can check here https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/

0


source


Put your data into the form and submit the form data with serializeArray()

0


source







All Articles