How to use FormData for AJAX file upload?
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
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, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
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.
Note: contentType: false
only available from jQuery 1.6 onwards
Sending formdata for file upload using ajax
use
$("#uploadForm").submit(function () {
var formData = new FormData(this);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Uploading both data and files in one form using Ajax?
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
Sending file together with form data via ajax post
Can you try using FormData()
:
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The above is a sample code, but you may use it to modify it.
Upload file using FormData and jQuery.ajax
Read Using FormData Objects
FormData takes the dom reference as the argument, not jQuery wrapper.
So try
aFormData = new FormData($("form").get(0));
also
aFormData.append($(this).attr("name"), $(this).val());
to get the value of an input you need to use .val() not .attr('value')
Also to append the file you need to add the file reference like
aFormData.append("filename", $('#filename').get(0).files[0]);
So your code might have to look like
function SubmitForm() {
var aFormData = new FormData();
aFormData.append("filename", $('#filename').get(0).files[0]);
$("form input").each(function(i) {
aFormData.append($(this).attr("name"), $(this).val());
});
$("form select").each(function(i) {
aFormData.append($(this).attr("name"), $(this).val());
});
......
}
JQuery / AJAX File Upload using FormData, file not posting
FormData
accepts a form
DOMElement, not a jQuery object. You need to call submitUploadFileForm()
just passing the this
reference to the form
:
submitUploadFileForm(this);
Upload files with ajax and existing form data
you can use FormData in:
var data = JSON.stringify(vm.data);
var fd = new FormData();
fd.append('data',data);
fd.append('file',vm.fileUploaded);
me.xhr({
headers: {'Content-Type': 'multipart/form-data'},
method: 'PUT',
url: 'swatch/' + vm.swatch.id + '.json',
callback: function(res) {
vm.saving = false;
try {
alert(res.message ? res.message : "Swatch saved successfully");
} catch (e) {
alert(res.message ? res.message : "Failed to save the changes, please try again.");
}
},
onerror: () => {
vm.saving = false;
alert('Failed to save the changes, please try again.');
},
data: fd
}
component:
<input type="file" @onchange="changed($event)">
new vue({
data:{fileUploaded:''},
methods:{
changed(event){
this.fileUploaded = event.target.files[0];
}
}
})
Simple file upload using Javascript FormData(), AJAX $.post and PHP
Follow below instruction:
- You should have an input with type file in your html part:
<input type="file" id="file_target">
- Add change event for file input
$('#file_target').change(function (e) {
e.preventDefault();
// for single file upload
uploadFile(this.files[0]);
// for multiple file upload
$.each(this.files, function (k, file) {
uploadFile(file);
});
});
- Add
uploadFile
function that can upload the file:
You can validate the file to be upload here
function uploadFile(file) {
// some validation like size or dimension
//...
var urlPath = 'php_script_file_for_upload';
// create data to be send
var fd = new FormData();
fd.append('file_data', file);
// if you do not want use jQuery
var xhr = new XMLHttpRequest();
// third parameter is set to be async request
xhr.open('POST', urlPath, true);
xhr.send(fd);
// if you do use jQuery
$.ajax({
method: 'POST',
url: urlPath,
data: fd
});
}
- PHP script file
if(!empty($_FILES['file_data']))
{
$path = "uploads/";
$path = $path . basename( $_FILES['file_data']['name']);
if(move_uploaded_file($_FILES['file_data']['tmp_name'], $path)) {
// successful upload
} else{
// error during upload
}
}
If you need no ajax approach please see https://gist.github.com/taterbase/2688850
How to send FormData objects with Ajax-requests in jQuery?
I believe you could do it like this :
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);
}
});
Notes:
Setting
processData
tofalse
lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.Setting the
contentType
tofalse
is imperative, since otherwise jQuery will set it incorrectly.
Related Topics
Should All Jquery Events Be Bound to $(Document)
Build Tree Array from Flat Array in JavaScript
How Does JavaScript Handle Ajax Responses in the Background
How to Get the Full Object in Node.Js'S Console.Log(), Rather Than '[Object]'
How to Sort an Array of Integers Correctly
How to Prevent a Parent'S Onclick Event from Firing When a Child Anchor Is Clicked
How to Identify If a Webpage Is Being Loaded Inside an Iframe or Directly into the Browser Window
How to Completely Uninstall Node.Js, and Reinstall from Beginning (Mac Os X)
How to Get the Current Date in JavaScript
How to Enable Cors in Angularjs
Link Tag Inside Browserrouter Changes Only the Url, But Doesn't Render the Component
How to Write Denormalized Data in Firebase
How May I Sort a List Alphabetically Using Jquery
How to Add Options to a Select from a JavaScript Object With Jquery
How to Create a File in Memory For User to Download, But Not Through Server