I have an existing HTML form that I'm trying to update to use jQuery.load(). How can I pass all of the elements of the form as POST parameters rather than having to specify which parameters to pass?
The form elements are created dynamically by a script and the number of elements as well as the name of the elements varies considerably to the extent that it's not practical to specify which parameters to pass via AJAX/POST. Is there a simple way to pass to jQuery.load() all of the elements within the <form></form>
tags as if the form was submitted traditionally?
Introduction to jQuery load () The load () method of jQuery is used to get data from the server and place the HTML or text response in an element in the DOM. So, basically it is a combination of two conventional methods of most scripting languages – the global get method and the respective methods to get the element in DOM and set their contents.
This event works with elements associated with a URL (image, script, frame, iframe), and the window object. Depending on the browser, the load event may not trigger if the image is cached (Firefox and IE). Note: There is also a jQuery AJAX method called load ().
$.ajax ( { type: "POST", url: "form.php", data: $ ("#form_id").serialize () success: function (msg) { alert ("Form Submitted: " + msg); } }); You can use jQuery.post ( url, data, callback, type), as its simpler to jQuery.ajax ( options ). By using serialize, you can send the whole form automatically.
There is a fundamental difference between when jQuery implements the load method with a selector appended to the url and without a selector appended to the url. In the former case, the scripts from the url are executed. Whereas in the latter case, the scripts are omitted.
Easy: When you gather your form data and past it as the second parameter to load()
, use serializeArray(data)
, and don't use serialize(data)
, as the currently accepted answer recommends.
serialize()
returns a string, whereas serializeArray()
returns an object.
load()
sends a POST if the data is an object. If data is a string, load()
sends a GET.
You can use .serialize()
to serialize all of the inputs of the form for submitting along with your jQuery.load() call.
$('form').serialize()
For example, using jQuery.load()
(only does GET unless you pass it an object for data, then POST)
$.load(
'postTo.php',
$('#yourFormId').serialize(),
complete(responseText, textStatus, XMLHttpRequest){
//do your processing after the fact
}))
Using, jQuery.ajax()
, you can make it POST
$.ajax({
'url': 'postTo.php',
'type': 'POST',
'data': $('#yourFormId').serialize(),
'success': function(result){
//process here
}
});
See: http://api.jquery.com/jQuery.ajax/
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