Home > Enterprise >  Sending post request using ajax and load the data into the same php file
Sending post request using ajax and load the data into the same php file

Time:09-21

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?

CodePudding user response:

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