Is there a way using jQuery to submit a form without the elaborate field by field breakdown?
I'm using jQuery to perform AJAX based page reloads on links - they bring up the "Loading..." div window and then close it when the content returns and load the content. This works exactly as expected.
I have several different forms in my project that I would like to submit using the same method - on submit brin开发者_运维技巧g up a "Loading..." div window and then close it when the content returns. Is there any way to do this without writing a custom function for each form? The samples I've seen require you to grab and encode each form field and pass it in the ajax method. Some forms only have a few fields, others have many so this would be a cumbersome process. I'd like it to just grab all fields in the form and submit them under the field names.
Any insight on this would be greatly appreciated!
It looks like you're looking for something along the lines of .serialize()
. It's basically jQuery's utility function for encoding form elements for an AJAX call or a GET query string.
Using that gets you something that looks like myinput=somevalue&myotherinput=someothervalue
based on the name
properties of your form elements. You can chuck that into whatever call you're making against your server, as long as they recognize the format (versus something like JSON data or a scalar string, for example).
It's pretty easy actually, you can do this:
$('form').serialize();
obviously you want to send it your form, but if you call serialize after selecting a form tag, it will serialize the form for you. You can then use that in your ajax call.
you can use serialize()
in this way
$('#formId').serialize();
Maybe one way can be using the $.serialize() function. You can write a function to execute when a form is submitted. For example, if you have three forms withd id "form1", "form2" and "form3":
$(document).ready(function()
{
$('#form1, #form2, #form3').submit(sendData);
});
function sendData()
{
var dataString=$(this).serialize();
$.ajax({
url: "url_to_send.php",
data: dataString
});
return false;
}
Have you read this?
http://api.jquery.com/jQuery.post/
$.post("test.php", $("#testform").serialize());
精彩评论