简体   繁体   中英

Send multidimentional array from JQuery AJAX to PHP

i want to send a multidimensional array to PHP from JQuery AJAX, but it is receiving in PHP like this

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

i must be doing some stupid mistake. here is the code. it gets records from a table and send 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 receiving the data:

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

Use JSON.stringify() instead of toString() like so:

Change your AJAX call to this:

$(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 as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.

Take this answer as a reference:

I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.

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 your ajax reponse, alert(data.a) would be alerting "1"

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 shows up in PHP's $_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 at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object

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

将数据放入表单并使用serializeArray()发送表单数据

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM