formdata jquery code example
Example 1: formdata js
var form = $('form')[0];
var formData = new FormData(form);
or specify exact data for FormData();
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false,
processData: false,
});
After this it will send ajax request like you submit regular form
with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all
files must be sent via POST request.
Example 2: javascript ajax post form data
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
Example 3: jquery form data
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});