How to send arrays using XMLHttpRequest to server
ajax, jquery, xmlhttprequest
Solution
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) );
Problem
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) ?