简体   繁体   中英

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

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. 在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM