Answer the question
In order to leave comments, you need to log in
How to send JSON to PHP via POST?
Recently, I decided to switch to native JS and ran into the problem of transferring data via AJAX. The task costs following: we have a certain object which should be transferred to the server.
JS code
var someObj = {a:1,b:2};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'node.php', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(someObj);
xhr.onreadystatechange = function(){
if (this.readyState == 4) {
if (this.status == 200)
console.log(xhr.responseText);
else
console.log('ajax error');
}
};
var someObj = {a:1,b:2};
$.ajax({
type: "POST",
url: "node.php",
data: someObj,
success: function(res) {
console.log(res);
}
});
print_r($_REQUEST);
Array
(
)
Array
(
[a] => 1
[b] => 2
)
Answer the question
In order to leave comments, you need to log in
Something like this:
js:
var someObj = {a:1,b:2};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'scratch.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('param=' + JSON.stringify(someObj));
xhr.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
console.log(xhr.responseText);
}
else
{
console.log('ajax error');
}
}
};
$param = json_decode($_REQUEST["param"]);
$result = "Результат: a = ".$param->a."; b = ".$param->b;
die($result);
jquery decomposes json into a regular post request: key=value&ke2=value2
And you just send an object in the native version, and you need to send a string there as above or a JSON generated string (parse in php via php//input).
Need Fiddler, Wireshark, etc. to analyze (debug) requests, compare them, understand what the problem is.
var str = "";
for (var key in someObj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(someObj[key]);
}
xhr.send(str);
Tell me, please, if it's not difficult. I need to implement something similar, but for now I just want the example to work
<?php
echo "<script type='text/javascript' src='testjson.js'></script>";
echo "<form action='testjson.php' method='post'>
<input type='text' name='param[]' value=''>
<input type='text' name='param[]' value=''>
<input type='submit' value='Отправить'>
</form>";
print_r($_REQUEST["param"]);
$param = json_decode($_REQUEST["param"]);
$result = "Результат: a = ".$param->a."; b = ".$param->b;
die($result);
Результат: a = ; b =
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question