3

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);
}
1
  • Just a comment on your philosophy. Don't think of it as sending data to PHP, but instead as two parts; sending data to server via HTTP/JavaScript, and using CGI script (in this case PHP) to read it. Commented Feb 6, 2016 at 21:41

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

im getting this error: Uncaught InvalidStateError: Failed to read the 'selectionDirection' property from 'HTMLInputElement': The input element's type ('checkbox') does not support selection.
the error was from this code but there was another error. i had to put .html() on table field like this "name = parent.find('td').eq(5).html();"
1

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"

Comments

0
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/

Comments

0

Put your data in a form and send form data with serializeArray()

1 Comment

Consider adding an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.