javascriptphpjqueryajax

jQuery ajax response not displaying when returning to current page


I'm attempting to post some data back to the same page through ajax. In the example below, the $name variable is not being updated in my page once the button is clicked. However, if I look at the console log of the response from ajax (using firebug) it shows the correct html, with the name inserted (i.e. <div>Matthew</div>) - the page just isn't being updated with this response. Any ideas for how to fix this would be greatly appreciated.

The code I have is:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>

<?php
$name = "A name";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $name = "No name!";
  }
  else{
    $name = $_POST["name"];
  }
}
?>

<script>
$(document).ready(function(){
    $("button").click(function(){ 
       var mydata = {name: "Matthew"}; 
       $.ajax({
          type: 'POST',
          data: mydata,
          success: function(data){
            console.log(data);
          }
        });
      
    });
});
</script>

<button>Send an HTTP POST request to a page and get the result back</button>

<div id="name">
<?php echo $name;?>
</div>

</body>
</html>

Solution

  • It is because <?php echo $name;?> does not run again when doing the ajax call. You have to replace the content of the div in the success function like this:

    success: function(data){
                $("div").html(data);
              }