Pass entire form as data in jQuery Ajax function
Solution 1:
There's a function that does exactly this:
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
Solution 2:
serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.
Suppose that we have a form with this id : "myform".
the better solution is to make a FormData and send it:
var myform = document.getElementById("myform");
var fd = new FormData(myform );
$.ajax({
url: "example.php",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
}
});
Solution 3:
In general use serialize()
on the form element.
Please be mindful that multiple <select> options are serialized under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
Solution 4:
Use
serialize( )
var str = $("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
Solution 5:
A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!
<form id='test' method='post' enctype='multipart/form-data'>
<input type='text' name='testinput' id='testinput'>
<button type='submit'>submit</button>
</form>
Your send function in jQuery would look like this:
$( 'form#test' ).submit( function(){
var data = new FormData( $( 'form#test' )[ 0 ] );
$.ajax( {
processData: false,
contentType: false,
data: data,
dataType: 'json',
type: $( this ).attr( 'method' );
url: 'yourapi.php',
success: function( feedback ){
console.log( "the feedback from your API: " + feedback );
}
});
to add data to your form you can either use a hidden input in your form, or you add it on the fly:
var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );