Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I send a JavaScript array as a JSON variable in my AJAX request?

Thank you.

share|improve this question

3 Answers

up vote 2 down vote accepted

This requires you to serialize the javascript array into a string, something that can easily be done using the JSON object.

var myArray = [1, 2, 3];
var myJson = JSON.stringify(myArray); // "[1,2,3]"
....
xhr.send({
    data:{
        param: myJson
    }
});

As the JSON object is not present in older browsers you should include Douglas Crockfords json2 library

If you already rely on some library that includes methods for encoding/serializing then you can use this instead. E.g. ExtJs has Ext.encode

share|improve this answer
So all it does it create a string: "[1,2,3]"... But what if I want to send a string that starts and ends with [], will the server side be able to tell the difference? – thedp May 11 '10 at 22:06
Did you not say JSON? That is per definition just the format of the content of a string. If you in fact wanted to send an array to the server then that is a different question. But having said that, if one of the elements in the array contains [ or ] then it will automatically be escaped by the serializing method. – Sean Kinsey May 11 '10 at 22:09
I tried a fixed example by sending the "[1,2,3]" string to the server using ajax/json. But when I check the received value with $val[0] it gives me: "[". Do I need to process the json array on the server side before I can use it? – thedp May 11 '10 at 22:40
1  
$val is still a string - if you want this as an array (with items of some type) then you will need to decode it. I'm guessing your using php so you could try json_decode php.net/manual/en/function.json-decode.php – Sean Kinsey May 11 '10 at 22:56
1  
One thing you need to remember is that in the browser you have ECMAScript (javascript), and on the server you have PHP (I'm guessing). These are different languages and hence has different types. JSON is a 'language' understood by both, but one that only supports a subset of each one. So only primitives like strings, numbers and booleans are supported as well as basic arrays, indexed and associative (literal object notation). – Sean Kinsey May 11 '10 at 23:00
show 1 more comment

If you're not using a javascript library (jQuery, prototype.js, etc) that will do this for you, you can always use the example code from json.org

share|improve this answer

Just encode the array and send it as part of your AJAX recuest:

http://www.openjs.com/scripts/data/json_encode.php

There are too many others encoders, or even plugins for JQuery and Mootools :D

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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