How to submit form using AJAX?
I have an event listener:
$('button.publish').live('click', function() {
//enter code here
});
This button
element is inside a form. I know that I can't use $(this).submit();
'cause it will cause refresh. I also can't target the form by its ID because I'm trying to make it for general use (add news, add contact, add ...).
Knowing this, I can use the form's action for this is different from each other but I don't know how to submit the form inside the button event listener using AJAX (using $.post()
).
Is this the correct use:
var form = $(this).closest('for开发者_StackOverflowm');
$.post(form.attr('action'), form.serializeArray(), callback, type);
Or there is a better way?
What you have is correct, you can use .serliaze()
to save a few steps on the jQuery side, like this:
var form = $(this).closest('form');
$.post(form.attr('action'), form.serialize(), function(data) {
alert("The response was: " + data);
});
I don't know an advanced way, but a simple way is to get each form element's data like with $("#bar").val(); quick example:
$.ajax({
type: "POST",
url: "some.php",
data: data: "bar="+$("#bar").val()+"&foo=bar",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
精彩评论