Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you override an existing html form to use jquery to post the form?

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>
like image 611
Chris Avatar asked Jun 03 '10 14:06

Chris


2 Answers

try reading this.

or

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

Reigel


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>
like image 40
Doug Neiner Avatar answered Oct 22 '22 14:10

Doug Neiner