-1

I can't receive data from AJAX request in my ajax.php file:

Here my AJAX request

window.addEventListener("DOMContentLoaded", (event) => {

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'src/ajax.php', true);
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function () {

        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            console.log(response);
        }

    };
    
    var test = { data: "test",};

    xhr.send(JSON.stringify(test));
});

And here the ajax.php :

    echo json_encode($_POST['test']); 

I choose to not use jQuery by the way because I don't want to.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 1
    Good code indentation and layout ___is for life, not just for Christmas___ and would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will be glad you took the time in the end. – RiggsFolly Jun 23 '23 at 07:15
  • What is in `$_POST` when you check? Anything at all? – droopsnoot Jun 23 '23 at 07:16
  • 2
    Try looking at `$_POST['data']` because thats what you called the variable in `var test = { data: "test",};` – RiggsFolly Jun 23 '23 at 07:16
  • @RiggsFolly except they JSON stringified it, so it won't be in $_POST... – ADyson Jun 23 '23 at 07:18
  • Trying to `json_encode` something which is already JSON makes no sense (even if you were trying to read it from the correct place). You'd need to _decode_ it. – ADyson Jun 23 '23 at 07:19
  • @ADyson Ahh missed that – RiggsFolly Jun 23 '23 at 07:24
  • @RiggsFolly that would just send the text "[object Object]" to the server as a string (see https://jsfiddle.net/082bjhwr/). XHR isn't as clever as newer AJAX libraries...OP would need to build their own form-url-encoded string first, and pass it in. And also remove the content-type header. – ADyson Jun 23 '23 at 07:26
  • I wrote an SQL request and I used console.log to display the results and it works. The problem I'm facing is I would like to pass a var to this SQL request in my JSON object but $_POST always returns empty array. It's like the ajax.js is not allowed to send data to the ajax.php – MatthieuIX Jun 23 '23 at 07:33
  • Php does not put json data into $_POST. Read the duplicate, please – ADyson Jun 23 '23 at 07:38

1 Answers1

-1

if you are sending

{data: "test"}

i guess in your php should be the code like this

echo json_encode($_POST)

or

echo $_POST['data']

cause there is no param named test in your request

Ghiya
  • 9
  • 2
  • There's no `POST` param named `data` either. Read the duplicate (in the blue box at the top, if you refresh your page) – ADyson Jun 23 '23 at 07:20