views:

4782

answers:

5

I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?

+8  A: 

You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.

You might want to take a look at Creating JSON Data in PHP

csexton
I found this as the best answer because it doesn't stick to any javascript framework in particular.
Lucia
doesn't even have to be XML or JSON either, you could post a CSV string or anything
annakata
The JSON-PHP library fuzzymonk hinted is outdated and faster implementation is already in PHP. See the manual for json_encode and json_decode functions.
Michał Rudnicki
+1  A: 

You may be looking for a way to Serialize (jQuery version) the data.

charlesbridge
Just to add some information, I could find the Protoype version of this piece of advise at http://www.prototypejs.org/api/object
Lucia
A: 

IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.

rmeador
A: 

You can create an array and send it, as Meador recommended: (following code is Mootooled, but similar in other libraries / plain old JS)

myArray.each(function(item, index)  myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());

That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']

echo $_POST['arrayItems'] ;

will echo something like: array=>{[0]=>'first thing', [1]=> second thing}

SamGoody
A: 

You might do that with $.post method of jQuery (for example) :

var myJavascriptArray = new Array('jj', 'kk', 'oo');

$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
   // do something with received data!
});

Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.

Is it that ?

Dragouf