简体   繁体   中英

Ajax post - Sent array as data to PHP

I need to pass a JSON array to to PHP, and receive it as $_POST['data'] . This will contain my data through json_parse .

I got an error, no clue what happens here. The Ajax call throws the following error:

 [object Object] parsererror SyntaxError: Unexpected token < 

My code:

function testJson() {
    var arr = { };
    arr['action'] =  "anaction";
    arr['type'] = "atype";


    $.ajax("test2.php", {
        type: "POST",
        data: JSON.stringify({ data: arr}),
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data) {
            $("#result").html(data);
        },
        error: function (a, b, c) {
            $('#error').html(a + " " + b + " " + c);
        }
    });

More info: The error mentioned before is from error function call.

Edited based on suggestions and testing the function now works like this:

function testJson() {
    var arr = { };
    arr['action'] =  "anaction";
    arr['type'] = "atype";


    $.ajax("test2.php", {
        type: "POST", 
        data:  {data : arr}, /* Stringify deleted and added an array there, i remove too a non needed json related stuff */
        success: function (data) {
            $("#result").html(data);
        },
        error: function (a, b, c) {
            $('#error').html(a + " " + b + " " + c);
        }
    });

Now I'm recieving the array in post as expected.

Dilemma, boths answers helps in the solution of the problem .

If you setting the dataType as 'json' in the ajax function, this means that the php file should return valid json. Use json_encode in your php file.

Multiple issues here:

var arr = { }; defines an object whereas var arr = [ ]; defines an array.

The use as arr['action'] = "anaction"; implies, that it is an object and not an array although named so.

Usually, jQuery is doing the job internally:

$.ajax("test2.php", {
    type: "POST",
    data: { "data": arr} } // no need to stringify anything here ...
    ...

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