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?
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
You may be looking for a way to Serialize (jQuery version) the data.
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.
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}
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 ?