Jim Jim - 7 months ago 23
Javascript Question

XMLHttpRequest: need to use success and error functions from ajax

I have this ajax post function run when an upload button is clicked, the files get uploaded to the server, the server sees for any errors and if there are erros, it notifies the user with the

req.end();
function. The problem is, since then, I've moved to
XMLHttpRequest()
(to use the onprogress functions that it provides) but I still need to use those success and error functions from ajax. Is there a way to use them somehow with
XMLHttpRequest
? Thank you!

This is the code I have so far:

var xhrVideo = new XMLHttpRequest();
xhrVideo.open('POST', '/uploadVideo', true);
xhrVideo.upload.onprogress = function(e) {
if (e.lengthComputable) {
$('.videoProgress').html(((e.loaded / e.total) * 100).toFixed(0)+'%');
}
};
var videoForm = new FormData($('.videoUploadForm')[0]);
xhrVideo.send(videoForm);


And the ajax code:

var videoData = new FormData($('.videoUploadForm')[0]);
$.ajax({
url: '/uploadVideo',
type: 'POST',
data: videoData,
cache: false,
contentType: false,
processData: false,
mimeType:"multipart/form-data",
success: function(data){
switch(data){
case '1':
alert('Wrong Video File Extension');
break;
case '2':
alert('Wrong Image File Type');
break;
}
},
error: function(data){
alert('Something went wrong! Please reload this page')
}
});

Answer

Use listeners for load and error events.

Example adding a listener for success event.

xhrVideo.addEventListener('load', function(e) {

NOTE: the listeners must be added before the send() function

Also, I advise you to read the entire article about using XMLHttpRequest().

Comments