user1620429
user1620429

Reputation:

How to send arrays using XMLHttpRequest to server

As I know using ajax you can send data to the server but I'm confused about sending an array to post using XMLHttpRequest not any library like jQuery. My question is that, is that possible to send an array to php using XMLHttpRequest and how does jQuery send an array to php, I mean does jQuery do any additional work to send an array to server (php $_POST) ?

Upvotes: 12

Views: 34315

Answers (4)

Mr.Noino
Mr.Noino

Reputation: 31

An alternative way, if you want to use the x-www-form-urlencoded content type to send data through AJAX to PHP, you must do something like this:

var array = [1, 2, 3];

//variable to concat POST parameters
var params = "";


for(var i = 0; i < array.length; i++){

  params += "array[]=" + array[i] + "&";

}

//Remove the last char which is '&'
params = params.substring(0, params.length -1);

var http = new XMLHttpRequest();

http.open("POST", "http://localhost/your_script.php");

http.onload = function (){

    //if response status is OK
    if(http.status === 200){
  
        console.log(JSON.parse(http.response));
  
    }else{
  
        //handle response if status is not OK
  
    }

};

//set content type as x-www-form-urlencoded
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//send the request with parameters
http.send(params);//params = "array[]=1&array[]=2&array[]=3"

your_script.php:

<?php
//check if index "array" on POST is defined
if(isset($_POST["array"])){

    //write a JSON body
    echo json_encode(["message" => "Received"], JSON_FORCE_OBJECT);

}

Upvotes: 1

Esailija
Esailija

Reputation: 140234

Well you cannot send anything but a string of bytes. "Sending arrays" is done by serializing (making string representation of objects) the array and sending that. The server will then parse the string and re-build in-memory objects from it.

So sending [1,2,3] over to PHP could happen like so:

var a = [1,2,3],
    xmlhttp = new XMLHttpRequest;

xmlhttp.open( "POST", "test.php" );
xmlhttp.setRequestHeader( "Content-Type", "application/json" );
xmlhttp.send( '[1,2,3]' ); //Note that it's a string. 
                          //This manual step could have been replaced with JSON.stringify(a)

test.php:

$data = file_get_contents( "php://input" ); //$data is now the string '[1,2,3]';

$data = json_decode( $data ); //$data is now a php array array(1,2,3)

Btw, with jQuery you would just do:

$.post( "test.php", JSON.stringify(a) );

Upvotes: 17

PinnyM
PinnyM

Reputation: 35541

That depends on the protocol you choose to package your data structure. The 2 most commonly used are XML and JSON. Both have ways to declare an array:

JSON: ['one thing', 'another thing']

XML: <things><thing name='one thing' /><thing name='another thing' /></things>

and neither will take any significant extra work by the server. In many cases it will actually reduce work since you don't need to use a naming convention to differentiate between them.

Upvotes: 1

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

You want to send a jSon object (which can be an array). Check this out if you are using php Send JSON data to PHP using XMLHttpRequest w/o jQuery.

More about jSon: http://json.org/

jQuery jSon sample: JQuery and JSON

Upvotes: 0

Related Questions