0

index.php file:

<?php
    $content = file_get_contents("php://input");
    $object = json_decode($content);

    echo var_dump($object);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <button onclick="hello()"> noice </button>    

    <script>
        function hello() {
            const data = {hello: "world"};

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "index.php");
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send(JSON.stringify(data));
        }

    </script>
</body>
</html>

from index.php sending a ajax post request with some data to the same index.php and trying to view the fetched data from index.php file but nothing happens. But the file is received by the browser and not updating. enter image description here

My question is am I doing something wrong? and how to achieve this?

6
  • What are you expecting to "update"? There's no code which reads the result of the AJAX request or does anything with it. Commented Sep 20, 2022 at 17:04
  • the php code above accepting the data but not updating the current view. I just want updated view after accepting the data, like the right side of the pic Commented Sep 20, 2022 at 17:09
  • 1
    You have just initiated the xhr call, but have not used the callback to interact with the response.. See here developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/… Commented Sep 20, 2022 at 17:10
  • @altair00: You would update the current page in JavaScript. PHP is no longer involved in rendering the page after it's already been delivered to the browser. Commented Sep 20, 2022 at 17:11
  • 1
    @altair00: Define "the whole view". If the goal is to reload the page entirely then don't use AJAX, just use a normal form POST. If the goal is to modify the data of a specific element on the page then you would want to target that specific element. Currently the data you're looking to see isn't really part of the "page", it's just dumped to the output before the page even begins. Additionally, the AJAX response is going to have that same unstructured data. You'll want to start by creating structure in your HTML and your AJAX response (ideally JSON in the latter). Commented Sep 20, 2022 at 17:21

1 Answer 1

1

Could not write a lot in comment... here is how you do it...

First of all where you do the var_dump, put that code block within a IF() statement and do an exit(), so that when the script receives a POST request, it just dumps the variable and stop execution, otherwise you will receive the full page contents (including all htmls) in your ajax response..

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
       $content = file_get_contents("php://input");
       $object = json_decode($content);
 
       echo var_dump($object);
       exit();
    }
?>

and then at the ajax part, handle the response like..

xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        //Do anything you want with => this.responseText
        // If you want to update the whole view, you can do like 
        document.getElementsByTagName('body').item(0).innerHTML = this.responseText;
   }
};
xhr.send(JSON.stringify(data));
Sign up to request clarification or add additional context in comments.

2 Comments

It worked thanks. Since you have got my question right, I am just wondering is there any way to improve this using something else? because now every time I am clicking the button and new index.php is being sent out to the browser.
Hi @altair00 I forgot the add the exit() after var_dump(); just added that.. You should be good now.. But try to keep the ajax things in a separate file. You can call it ajax.php and just have some PHP code there (no HTML).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.