1

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>
matt tuman
  • 83
  • 1
  • 5
  • 14
  • One last question. I added a simple form to my code above. Would I just change name:"Mike" to term = $form.find( 'input[name="name"]' ).val(),? Thanks again! – matt tuman Jul 26 '13 at 16:46

2 Answers2

2

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/).

putvande
  • 15,068
  • 3
  • 34
  • 50
2

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.

totallyNotLizards
  • 8,489
  • 9
  • 51
  • 85
  • One last question. I added a simple form to my code above. Would I just change name:"Mike" to term = $form.find( 'input[name="name"]' ).val(),? Thanks again! – matt tuman Jul 26 '13 at 16:44
  • @matttuman yes you can do that, but a better way would be to use jquery's `$.serialize()` function to send form data if you just want to submit the data in the form. I'll update my answer to show how... – totallyNotLizards Jul 29 '13 at 13:55