V
V
Valera Udav2016-06-02 15:22:03
JavaScript
Valera Udav, 2016-06-02 15:22:03

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');
  }
};


Similar jQuery code
var someObj = {a:1,b:2};
$.ajax({
  type: "POST",
  url: "node.php",
  data: someObj,
  success: function(res) {
    console.log(res);
  }
});


We accept data in PHP
print_r($_REQUEST);

As a result, we have a non-working code in native JS and a working code in jQuery. In the first case (JS) always returns to the console:
Array
(
)

In the second (jQuery):
Array
(
    [a] => 1
    [b] => 2
)


No matter how I torture my JS, it doesn't want to return anything. Could you tell me what could be the problem or at least in which direction should I look?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
O
OVK2015, 2016-06-02
@TARAKANhoy

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');
    }
  }
};

php:
$param = json_decode($_REQUEST["param"]);
$result = "Результат: a = ".$param->a."; b = ".$param->b;
die($result);

A
Alexander Aksentiev, 2016-06-02
@Sanasol

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).

R
Rou1997, 2016-06-02
@Rou1997

Need Fiddler, Wireshark, etc. to analyze (debug) requests, compare them, understand what the problem is.

V
Vladimir Grabko, 2016-06-02
@VGrabko

var str = "";
for (var key in someObj) {
    if (str != "") {
        str += "&";
    }
    str += key + "=" + encodeURIComponent(someObj[key]);
}
xhr.send(str);

L
Love, 2017-09-27
@iamy

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);

this thing, if you enter data into the form, it displays an array:
But the result is empty: Результат: a = ; b =
I suspect that I made the form incorrectly, can you tell me what is wrong?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question