Ajax和PHP同页不起作用

I am trying to send a JSON object via ajax to the same page. While running my code, the ajax function does seem to send the data, as I can see on the response, that the $id in the PHP code, is changed to 200, but I am unable to display it on the webpage. I have included the jquery.js file (I'm not sure if I need to add another js library or not). I tried looking at a lot of stackoverflow answers but was unable to solve my problem. Any help would be appreciated.

PHP Code:

   <?php
        if(isset($_POST['area_id'])){
            $id = $_POST['area_id'];
            echo "Area ID: ".$id;
        } else {
            echo "test";
        }
    ?>

JQuery AJAX

var dat = {area_id: 200, title: 'title'};
$.ajax({
    type:"POST",
    data: dat,
    success:function(res){
        alert(res);
    }
});

[based on comments to the question...]

Your page isn't being updated because you've written no code to update it. echo simply emits text to the output, and alert() simply displays text to the user in a message box. In order to update the page client-side you'll need to write code which does that.

For example, if you have an element with id="output" and want to set the response text to that element, you'd do this:

$('#output').text(res);

That element would then get that text:

<div id="output">Area ID: 200</div>

Server-side code has no way of altering a page that's already been sent to the browser. When your client-side code receives new data via AJAX, that client-side code needs to use that data in whatever way you want it to.

Replace alert(res); with your display code. For example, suppose you want to display the ajax response in a div in the HTML:

<div id="display-div"></div>

then the javascript you need is

$('#display-div').html(res);

If you're sending AJAX request to the same page, you should exit() your PHP script:

<?php
    if(isset($_POST['area_id'])){
        exit("Area ID: " . trim($_POST['area_id']));
    }
    echo "test";
?>

This way, you're ensured that nothing else is printed out in a response. Otherwise the entire HTML page (including scripts) will be sent back.


Then you can inject your response into DOM using @David's example.