How can I use jQuery to submit a form without refreshing?
i have this form:
<form id="myform" name="myform" action="test.php" method="post">
<inp开发者_StackOverflow中文版ut type="text" name="shout-in" id="proShoutIn" maxlength="80" />
<a href="#" id="add_shout"><img src="post.gif"/></a>
</form>
how can i do a ajax post so that i can use if (isset($_POST['shout-in'])){..do something..}
?
i need to get the value that gets entered in the <input>
and do a post with it.
any ideas? thanks
$('#add_shout').click(function () {
var $form=$('#myform');
$.post($form.attr('action'), $form.serialize());
});
- $.post() -
$.ajax()
shorthand for the POST method - .serialize() - creates a text string in standard URL-encoded notation
With the 3rd (optional) parameter of $.post()
you can specify a callback function which will receive anything that was sent back as its only parameter. It will run when the AJAX query successfully finished (so you can do DOM modifications that depend on the AJAX call, etc.).
You also might want to prevent default form submission (in a lot of browsers pressing Enter in the input field would trigger it) and run the AJAX submission:
$('#myform').submit(function (e) {
$('#add_shout').click();
e.preventDefault();
});
$.post("test.php", $("#myform").serialize(),
function(data) {
// do something with the response
}
);
$("#myform").submit(function (e) {
$.post(this.action, $(this).serialize(), function (data) {
//handle response
});
//prevent form from submitting. In jQuery, do not use return false
e.preventDefault();
}
Nettuts plus:
Submit A Form Without Page Refresh using jQuery
精彩评论