Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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 ?

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

jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:

here is the synatax:

jQuery.ajaxSetting.traditional = true;

here is the example

$.ajax({    
 traditional: true,
 type: "post",
 url: myURL,
 dataType: "text", 
 data: dataToSend, //this will be an array eg. 
 success: function(request) {
  $('#results').html(request);
 }  // End success
 }); // End ajax method

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}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top