How to send arrays using XMLHttpRequest to a server

As I know, using ajax, you can send data to the server, but I'm confused by sending an array for publication using XMLHttpRequestnot some library like jQuery. My question is, is it possible to send an array to phpusing XMLHttpRequestand how jQueryto send an array to php, I mean, does jQuery do any additional work of sending the array to the server (php $ _POST)?

+5
source share
3 answers

Well, you cannot send anything but a string of bytes. "Sending arrays" is done by serializing (creating a string representation of the objects) of the array and sending it. Then the server will analyze the string and re-build the memory objects inside it.

Therefore, sending [1,2,3]to PHP can happen like this:

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 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) );
+10
source

It depends on the protocol that you have chosen 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 none of them will take significant additional work on the server. In many cases, this will actually shorten the work, since you do not need to use the naming convention to distinguish between them.

+1
source

You want to send a jSon object (which can be an array). Check this if you are using php Submit JSON data to PHP using XMLHttpRequest without jQuery .

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

jQuery jSon sample: jQuery and JSON

0
source

All Articles