Keval Bhatt
Keval Bhatt

Reputation: 6322

How to Distinguish a User-Aborted Call from an Error (jquery file upload)

I am using jQuery file upload plugin

this.manualPostData.submit().
    done(function(data, textStatus, jqXHR) {
         FSUtils.smartSuccess({
            content: Localize.tt('msg.uploadfile'),
            timeout: 6000
        });

    }).
    fail(function(jqXHR, textStatus, errorThrown) {
       FSUtils.smartError({
          content: JSON.parse(jqXHR.responseText).msgDesc,
           timeout: 6000
        });
    }

My scenario is when I call .submit() of my file object it will send a request to the server and the file will be uploaded successfully, but if the user clicks on cancel button at the time of uploading then I cancel my server request and it is handled by .fail().

How can I know if the request is aborted by the user? When the request fails then jqXHR parameter has data but when the request is canceled by the user then jqXHR parameter is undefined so how to handle and how to check if it is aborted by the user ?

I cancel a server request using these two lines

 this.manualPostData.abort()
 this.manualPostData = null

Upvotes: 1

Views: 142

Answers (1)

Keval Bhatt
Keval Bhatt

Reputation: 6322

The trick is to check the response headers in the XMLHttpRequest object. If there are no response headers (null or empty string, depending on the browser), the server did not respond yet. That means the user aborted.

Here’s a function that takes an XMLHttpRequest and tells you if the user aborted it.

function userAborted(jqXHR) {
  return !jqXHR.getAllResponseHeaders();
}

Now in your .fails callback call this userAborted function

.fail(function(jqXHR, textStatus, errorThrown) {
   if (!userAborted(jqXHR)) {
     alert('Normal Fail');
   }else{
     alert('User Aborted');
   }
 }

You can’t use textStatus and errorThrown to tell if the user aborted. They return the same values whether the user aborted or the server returned with an error.

(I only tested a 500 error.)

Upvotes: 1

Related Questions