views:

60

answers:

3

I have a simple form that I am currently posting back to the server to update a nickname. What jquery code do I add (without changing the form) so that the page will not refresh, but instead jquery will post the form in the background and then pop up an alert message containing the reply back from the server?

<form method="post" action="http://www.myserver.com/update_nickname" name="input">
    Quick form to test update_nickname:<br>
    New nickname:<input type="text" value="BigJoe" name="newNickname"><br>
    <input type="submit" value="Submit">
</form>

<script src="jquery-1.4.2.min.js" type="text/javascript"> </script>
+2  A: 

You need to use jQuery to bind to the "submit" event and prevent the default action. It would be a little more efficient if your form and nickname input used id's in addition to their names:

<script type="text/javascript">
    jQuery(function($){
      $("form[name=input]").submit(function(e){
        e.preventDefault(); // Keep the form from submitting
        var form = $(this);

        // Use the POST method to post to the same url as
        // the real form, passing in newNickname as the only 
        // data content
        $.post( form.attr('action'), { newNickname: form.find(':text').val() }, function(data){
          alert(data); // Alert the return from the server
        }, "text" );
      });
    });
</script>
Doug Neiner
+1  A: 

try reading this.

or

$("form").submit(function(e){
    var form = $(this);
    $.ajax({ 
         url   : form.attr('action'),
         method: form.attr('method'),
         data  : form.serialize(), // data to be submitted
         success: function(response){
            alert(response); // do what you like with the response
         }
    });
    return false;
 });
Reigel
A: 

There's a plugin just for this.

http://jquery.malsup.com/form/

Tesserex