1

I'm tring to send a JSON to a PHP page via jQuery, but it doesn't work properly:

json_data = {};
json_data.my_list = new Array ();

$('#table_selected tr').each (function (i) {
    json_data.my_list.push ({id:$(this).attr("id")});
});

$.post ("my_page.php", json_data, function (response) {
    if (response) alert("success");
    else alert("error");
});

<?php
// this is my_page.php
$json = json_decode (stripslashes ($_REQUEST['my_list']), true);
echo var_dump($json);

?>

This returns NULL to my callback, where I'm wrong?

vitto
  • 19,094
  • 31
  • 91
  • 130

3 Answers3

2

you don't need the echo before var_dump

Andy
  • 29,707
  • 9
  • 41
  • 58
2

JSON is a string representation of JavaScript objects. You're sending something that looks like this:

{my_list: [{id: 'foo'}, {id: 'bar'}, {id: 'baz'}]}

Which is not JSON. This is JSON:

'{"my_list": [{"id": "foo"}, {"id": "bar"}, {"id": "baz"}]}'

I would recommend using json2.js (more info). This can be facilitated using .serializeArray().

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

json_data is a literal with an array inside that you put as parameter to the post, and will be sent as encoded array in the post request to the server.

In my_page.php you may want to look at $_POST array.

UPDATE: Ehm, I re-read your question and I'm not completely sure of what I wrote. What I said applies to GET request, and I believe also to post requests.

Minkiele
  • 1,260
  • 2
  • 19
  • 32