javascript tutorial - [Solved-5 Solutions] jQuery Ajax File Upload - javascript - java script - javascript array
Problem:
Can we use the following jQuery code to perform file upload using post method of an Ajax request ?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
click below button to copy the code. By JavaScript tutorial team
If it is possible, do we need to fill "data" part? Is it the correct way ? We only post the file to the server side. We have been Googling around, but what we found was a plugin while in my plan we do not want to use it. At least for the moment.
Solution 1:
file upload is not possible through ajax. We can upload file, without refreshing page by using IFrame. UPDATE: With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers. FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safarwe 5+, Opera 12+
Solution 2:
An AJAX upload is indeed possible with XMLHttpRequest(). No iframes necessary. Upload progress can be shown.
Solution 3:
- Use a hidden iframe and set our form's target to that iframe's name. This way, when the form is submitted, only the iframe will be refreshed.
- Have an event handler registered for the iframe's load event to parse the response.
Solution 4:
In case we want to do it like that:
$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
if( progressEvent.lengthComputable) {
var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
if( upload) {
console.log( percent + ' uploaded');
} else {
console.log( percent + ' downloaded');
}
}
})
.done( function() {
console.log( 'Finished upload');
});
click below button to copy the code. By JavaScript tutorial team
Solution 5:
$("#submit_car").click( function() {
var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
url: 'car_costs.php',
data: formData,
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
},
}) return false;
});