up vote -1 down vote favorite

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.

flag

2  
Did you try it? – Gumbo Jan 26 at 10:45

3 Answers

up vote 3 down vote

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

link|flag
read my updated post. – noname Jan 26 at 11:14
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 Jan 26 at 12:28
up vote 0 down vote

You can always serialize the array like so:

books: $.param(books)

Which works as follows:

$.param({a: [1, 2]}) // output: "a=1&a=2"
link|flag
up vote 0 down vote

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

link|flag
yes i tried, it didnt seem to work. – noname Jan 26 at 10:49
but how? read my updated post. – noname Jan 26 at 11:17

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.