I looked at the next stream
jQuery Ajax - Status Code 0?
However, I could not find a definitive answer, and I had serious problems finding the source of my problem, so I am posting here in the hope that someone can point me in the right direction.
In my code, I execute an Angular HTTP message that just sends the underlying JSON data, and then in the on success callback I use AJAX to upload the files to the same server. (I know that I should not use jQuery and Angular, but I cannot change this at the moment)
It looks something like this.
var deferred = $q.defer() // first post $http.post(url,payload,{params: params, headers: headers) .then(function(response) { uploadFiles(response,deferred); // I am also sending google analytics events here }, function(error) { // do error stuff } return deferred.promise; // upload files function function uploadFiles(response,deferred){ $ajax({ type: 'POST', processData: false, contentType: false, data: data // this new FormData() with files appended to it, url: 'the-endpoint-for-the-upload', dataType: 'json', success: function(data) { // do success stuff here deferred.resolve(data); }, error: function(jqXHR, textStatus, errorThrown) { var message = {}; if (jqXHR.status === 0) { message.jqXHRStatusIsZero = "true"; } if (jqXHR.readyState === 0) { message.jqXHRReadyStateIsZero = "true"; } if (jqXHR.status === '') { message.jqXHRStatusIsEmptyString = "true"; } if (jqXHR.status) { message.jqXHRStatus = jqXHR.status; } if (jqXHR.readyState) { message.jqXHRReadyState = jqXHR.readyState; } if (jqXHR.responseText) { message.jqXHR = jqXHR.responseText; } if (textStatus) { message.textStatus = textStatus; } if (errorThrown) { message.errorThrown = errorThrown; } message.error = 'HTTP file upload failed'; logError(message); deferred.resolve(message); } } }) }
Not my exact code, but almost the same.
The problem is that it works almost all the time, but maybe three or four out of every few hundred will fail. By mistake, I mean that the error handler function is called in the file upload function, and the files do not load.
I get jqXHRStatus 0 and jqXHRReadyState 0 when this happens.
The only way I can replicate the problem is to click the update in the browser when processing the request, however, users have reported that they do not (although 100% confirm this)
Perhaps there is a serious flaw in my code that I don't see? Maybe passing a pending variable around is not good practice? Or another way to invalidate an ajax request that I am not considering? Can Google analytics events be sent simultaneously?
Any advice would be great and please let me know if you would like more information on this issue.