1

I'm passing an array on a POST request using jQuery, however I don't understand how to do the same with "vanilla" javascript. This is my jQuery:

    // Request using jQuery
$.ajax({type:'POST',url:'insert-user.php',data: {myArray: myArray},
success:function(data_response){
    console.log("jQuery, got data back, response: "+data_response);
}});

This is currently how I'm trying to do it with plain js:

// Request using plain js
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        console.log("JS, got data back, response: "+xmlhttp.responseText);
    }
}
xmlhttp.open("POST","insert-user.php",true);
xmlhttp.send({myArray: myArray});
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

2 Answers2

3

Use this:

xmlhttp.send('myArray='+JSON.stringify(myArray));

At php side,

$array= json_decode($_POST['myArray']);
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
  • I did this, however I don't know how to decode it on my php file, I'm getting something like this: `Array ( [myArray] => {\"email\":\"lisandro.vaccaro@gmail.com\",\"first_name\":\"Lisandro\",\"last_nam‌​e\":\"Vaccaro\"} )` I tried json_decode and urldecode – lisovaccaro Oct 17 '13 at 15:30
2

The .send() method accepts a string which is the POST data to be sent in the request. In jQuery, the data property allows you to pass an object (which you have), but behind the scenes, jQuery converts the object into a key/value pairs format.

This is the format that you must pass to .send() because it doesn't automatically convert objects into the key/value string.

For example, to send myArray with three elements:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send('myArray[]=first&myArray[]=second&myArray[]=third');

Remember to include the header, to tell the server side which format you are sending POST data in.

A function to convert a simple 1 dimensional array to this format could look like:

function arrayToKeyValueString(name, arr){
    var str = name + '[]=';
    for(var i=0; i<arr.length; i++){
        arr[i] = encodeURIComponent(arr[i]);
    }

    str += arr.join('&' + name + '[]=');
    return str;
}

var myArray = ['one', 'two', 'three'];

console.log( arrayToKeyValueString('myArray', myArray) );
// outputs: myArray[]=one&myArray[]=two&myArray[]=three 

When working with plain Javascript ajax, it's often easier to just JSON encode data and send the string instead of trying to build the key/value string.

xmlhttp.send('myArray=' + encodeURIComponent(JSON.stringify(myArray)));
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • I tried to do this, I'm printing the $_POST variable on the requested file and logging it in the console. However I'm getting an empty array – lisovaccaro Oct 17 '13 at 14:35
  • See my edit - try adding the `Content-type` header to tell PHP that it's URL encoded key/value format. – MrCode Oct 17 '13 at 14:38
  • thanks, I tested both options. (I had to modify the second one a bit to send an associative array). However on my PHP I ended up with something like this, which I don know how to decode: `Array ( [myArray] => {\"email\":\"lisandro.vaccaro@gmail.com\",\"first_name\":\"Lisandro\",\"last_name\":\"Vaccaro\"} )` how can I turn it into a php array? – lisovaccaro Oct 17 '13 at 15:28
  • Try, `$phpObject = json_decode(stripslashes($_POST['myArray']));`. You can then do `echo $phpObject->email;`. – MrCode Oct 17 '13 at 15:30
  • The above will decode it to a PHP object. To get an array: `$phpArray = json_decode(stripslashes($_POST['myArray']), true);` So you can do `echo $phpArray['email'];`. – MrCode Oct 17 '13 at 15:33