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?

3 Answers 3

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().

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

Comments

2

you don't need the echo before var_dump

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.