views:

115

answers:

3

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

Thank you.

+1  A: 

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

timdev
+1  A: 

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

Cristian
+2  A: 

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

Sean Kinsey
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
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
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
$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 http://php.net/manual/en/function.json-decode.php
Sean Kinsey
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
Got it. Sorry for the obvious questions, still learning :)
thedp