views:

84

answers:

3

i want to send a javascript array to php using jquery ajax.

$.post("controllers/ajaxcalls/users.php",
{
    links: links
});

where the second 'links' is a javascript array.

when i've got this array:

'1' ...
    '1' => "comment1"
    '2' => "link1"
    '3' => "link2"
    '4' => "link3"
'2' ...
    '1' => "comment2"
    '2' => "link4"

then using:

var jsonLinks = JSON.stringify(links);
alert(jsonLinks);

will give me:

[null,[null,"comment1","link1","link2","link3"],[null,"comment2","link4"]]

seems to me that something is wrong. and i cant use json_decode on php side to get the elements.

what function should i use to convert it to json and how do i access it on the php side? have struggled with this in some hours now...would appreciate some help.

+3  A: 

You could use json_decode to read the passed json value. Take a look at this post.

Darin Dimitrov
read my updated post.
weng
In your updated post the array you show is not valid javascript. Please post the real javascript code you use to assign the array.
Darin Dimitrov
A: 

You can always serialize the array like so:

books: $.param(books)

Which works as follows:

$.param({a: [1, 2]}) // output: "a=1&a=2"
David Hedlund
A: 

I'm not sure if your example will work (did you try it?) If not, you can use json to send your array, and then decode it with php (http://www.php.net/manual/en/function.json-decode.php)

As written on the JSON website: The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

Values that do not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

Full page can be found here: http://www.json.org/js.html

joggink
yes i tried, it didnt seem to work.
weng
but how? read my updated post.
weng