I have an array that has a structure similar to the following:
var data = [
{
'name': 'Foo'
},
{
'name': 'Bar'
}
]
And I want to pass it to my php script with pure Javascript without relying on jQuery.
So my jQuery version would be:
$.ajax({
'url': '/script.php',
'method': 'POST',
'data': {'inscriptions': data},
'dataType': 'json',
'success': function(response){
// my code for handling the response
}
});
And in Javascript I have the following:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/script.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
xhr.onreadystatechange = function(event){
if(event.target.readyState != XMLHttpRequest.DONE)
return;
// my code for handling the response
};
However the issue I'm having is that sending it this way in Javascript, my $_POST
on the server side is empty because the
array(0){}
And if I change it to:
xhr.send(JSON.stringify({'inscriptions': data}));
Then on my server side my $_POST
will be:
array (size=1)
'{"inscriptions":' =>
array (size=1)
'{"name":"Foo"},{"name":"Bar"}' => string '' (length=0)
When I send it via jQuery I get the following:
array (size=1)
'inscriptions' =>
array (size=2)
0 =>
array (size=1)
'name' => string 'Foo' (length=3)
1 =>
array (size=1)
'name' => string 'Bar' (length=3)
Is there a way to achieve the same thing with pure Javascript?
My questions has been marked as a duplicate of Send JSON data from Javascript to PHP? but the answer doesn't answer my question. They are using a way to 'bypass' it with:
php://input
However, it's not sending it directly to the $_POST
like jQuery does.