I have a jQuery ajax function and would like to submit an entire form as post data. We are constantly updating the form so it becomes tedious to constantly update the form inputs that should be sent in the request.
-
Moh is correct about FormData() and images. But to clarify further. It is that serialise only works on strings (not binary data). the FormData() function works with forms that have the encoding type set to "multipart/form-data". Details here: developer.mozilla.org/en-US/docs/Web/API/FormDatajames kenny– james kenny2017-01-31 12:48:09 +00:00Commented Jan 31, 2017 at 12:48
8 Answers
There's a function that does exactly this:
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
6 Comments
person[0].firstName person[0].lastName person[1].firstName person[1].lastName<input name="person[1].lastName"> ?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:
let myform = document.getElementById("myform");
let fd = new FormData(myform );
$.ajax({
url: "example.php",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
// do something with the result
}
});
5 Comments
form.serialize() but it just didn't work for file upload. new FormData(this) worked nicelyurl: myform.action?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.
2 Comments
Use
var str = $("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
Comments
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' );
1 Comment
url: $(this).attr('action'), insteadYou just have to post the data. and Using jquery ajax function set parameters. Here is an example.
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'your_complete url',
data: $('form').serialize(),
success: function (response) {
//$('form')[0].reset();
// $("#feedback").text(response);
if(response=="True") {
$('form')[0].reset();
$("#feedback").text("Your information has been stored.");
}
else
$("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
}
});
});
});
</script>
Comments
Best way to Pass All Inputs to Form Data Object ( text , hidden , radio And Text Area) :)
function pass_all_inputs_form_data(form_id) {
var form_data = new FormData();
var inputs = $('#' + form_id)[0].getElementsByTagName("input")
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'radio') {
if (inputs[i].checked == true) {
}
} else {
form_data.append(inputs[i].id, inputs[i].value);
}
}
var textareas = $('#' + form_id)[0].getElementsByTagName("textarea")
for (i = 0; i < textareas.length; i++) {
form_data.append(textareas[i].id, $('#' + textareas[i].id).val());
}
return form_data;
}
Comments
The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.
My solution:
<form id="form_1" action="result.php" method="post"
onsubmit="sendForm(this.id);return false">
<input type="hidden" name="something" value="1">
</form>
js:
function sendForm(form_id){
var form = $('#'+form_id);
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(result) {
console.log(result)
}
});
}