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>
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;
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With