Question

Hi Im trying to learn how to do a post request using the simple example below. While I can easily post the data to result.php and get the results back via an alert message I'd like to return the results in a div on the current page instead. The reason for this is that I'd like the user to see their name appear on the screen as soon as they click on the button. Can someone tell me how I would modify this code so that the result of the post shows up in a div rather than as an alert message? Thanks

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
 $(document).ready(function(){
  $("#searchForm").submit(function(event){
    $.post("result.php",
     {
      name:"Mike"

      },
    function(data,status){
  //alert("Data: " + data + "\nStatus: " + status);
  $('#post-result').append(data);
      });
   });
  });
</script>

<form action="result.php" id="searchForm">
<input type="text" name="name" placeholder="Search..." />
<input type="submit" value="Search" />
</form>

<div id='post-result'></div>
Was it helpful?

Solution

Just put a div on the page and use jQuery's append() to place your data in it like so...

<div id='post-result'></div>

<script>
$(document).ready(function(){
    $("button").click(function(){
        $.post("result.php",
            $('#searchForm').serialize(),
            function(data,status){
                //alert("Data: " + data + "\nStatus: " + status);
                $('#post-result').append(data);
            }
        );
    });
});
</script>

UPDATE - as per comments, added call to serialize the form so that the script will post the current form data to the server on submit.

OTHER TIPS

You can do that in a lot of different ways, one of which could be:

$('#idofdiv').html(data);

If you replace alert("Data: " + data + "\nStatus: " + status); with the above code and replace idofdiv with your own div id it should work.

Have a look at the documentation of jQuery to learn more about it (http://api.jquery.com/).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top