0

I am trying to send an objet from javascript to php via ajax. My json seems correct and the php receives as far as I can tell what It should, yet I can't decode the object in php.

My js

const params = 'data=' + JSON.stringify(data)
console.log(params)

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', request, true);
xhr.onreadystatechange = function() {

    if(xhr.status==200){
        if(xhr.readyState>3) success(xhr.responseText);
    }

};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);

What my js in sending : data={"post_type":"post","tax_query":{},"meta_query":{"category":4}}

My php

$data = $_POST['data'];
var_dump($data);
$data = html_entity_decode($data);
var_dump($data);
$data = json_decode($data);
var_dump($data);

What my PHP is receiving in $_POST['data'] : string(73) "{\"post_type\":\"post\",\"tax_query\":{},\"meta_query\":{\"category\":4}}"

Yet when I try to json_decode I get NULL

I know there are a lot of posts on this already but I have seemed to have tried them all to no prevail. What am I doing wrong?

The Sloth
  • 367
  • 5
  • 18
  • 2
    If you're sending JSON then why are you setting the content type as application/x-www-form-urlencoded?? If you're sending JSON then set it to application/json - otherwise you're just going to confuse the server – ADyson Nov 02 '20 at 19:31
  • 2
    And when you've done that, next please read https://stackoverflow.com/questions/18866571/receive-json-post-with-php and amend your PHP code accordingly – ADyson Nov 02 '20 at 19:31
  • 2
    Oh and `const params = 'data=' + JSON.stringify(data)` should just be `const params = JSON.stringify(data)` - again, wrapping JSON inside URL-encoded parameters is nonsensical and the main cause of your problem – ADyson Nov 02 '20 at 19:33
  • 2
    It's also unlikely to be necessary to add the X-Requested-With header - the browser will probably do it for you – ADyson Nov 02 '20 at 19:34
  • 1
    Ok thanks that seems to have done it. I had previously tried with the changes you mentioned in the JS, but when I saw I wasn't receiving anything through `$_POST` I assumed that it wasn't working correctly, so I reverted back to this. Didn't realise you had to fetch the data with `file_get_contents('php://input')`. – The Sloth Nov 02 '20 at 20:11
  • Just curious, why was it not decoding? The response is correctly formatted is it not? – The Sloth Nov 02 '20 at 20:13
  • That I'm not sure about to be honest - tested in isolation it seems to work with the string you're reporting - demo: http://sandbox.onlinephpfunctions.com/code/f78c49ed3683f83f20bba28cf8771dc016c04e93 . But it's still a clunky workaround, better to do it sending just the JSON, as you've now got working. – ADyson Nov 02 '20 at 20:40

0 Answers0