darees darees - 2 months ago 8
jQuery Question

How to fix ajax xhr error in jquery

Basically I have a

type="file"
, I need to send chosen file through Ajax, But every time the form gets to submit I am getting a console error which says:

Error while submitting ajax

here is how I submit myform:

$(document).ready(function() {
$('form').submit(function(event) {
event.preventDefault();
checkforImage($('#Propicselecter_file'), "yes");
});
$('[type="file"]').change(function() {
var fileInput = $(this);
checkforImage(fileInput, "no");
});
});

function submit_form(){
var fileInput = $('#Propicselecter_file');
$.ajax({
url: '../propicuploader',
type: 'POST',
processData: false,
data: fileInput[0],
success: function(data){
}
});
}

function checkforImage(fileInput, submitornot){
if (fileInput.length && fileInput[0].files && fileInput[0].files.length) {
var url = window.URL || window.webkitURL;
var image = new Image();
image.onload = function() {
$("#NotPictureerror_spn").text("");
if(submitornot == "yes"){
submit_form();

}
};
image.onerror = function() {
$("#NotPictureerror_spn").text("Chosen file is not an image, Please Try Again");
};
image.src = url.createObjectURL(fileInput[0].files[0]);
}
}


Thanks in advance:)

Answer

Try passing a formData object instead of the file object:

var form_data = new FormData();
form_data.append('file', fileInput.files[0]);
$.ajax({
     url: '../propicuploader',
     type: 'POST',
     processData: false,
     contentType:false, // Added
     data: form_data,
     success: function(data){
   }
});