The script continues to run despite receiving an XHR error status of 0

I have created an asynchronous audio upload script that is working flawlessly, except for one issue that is really bothering me. The problem lies in the error handling aspect, where an error is being handled with an xhr status of 0 even though the upload process continues without any apparent errors.

xhr.upload.addEventListener("progress", keepPage(file,xhr),false);
xhr.upload.addEventListener("progress", uploadProgress,false);
xhr.upload.addEventListener("load", uploadComplete, false);
xhr.upload.addEventListener("error", uploadFailed(xhr.status), false);
xhr.upload.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "http://" + document.domain + "/script.php", true);
xhr.send(fd);
var uploading = true;
uploaded = false;
xhr.onreadystatechange=function(){
    if (xhr.readyState==4 && xhr.status==200) {
        var response = xhr.responseText;
        if (response == "success"){
            var uploaded = true;
            processSuccess();
        }
        else {
            var obj = $.parseJSON(response); //parse error JSON array
            errReport = obj.errReport
            uploadFailed(errReport);
        }
     }
}
uploading_tools(file, xhr, uploaded);

The error event seems to be triggered as soon as the upload starts. Upon adding console.log(xhr.status) in the uploadFailed function, a status of 0 is displayed.

Even though I know that an xhr status of 0 usually occurs when an ajax call is made across different domains, this doesn't seem to be the case here.

If I am unable to resolve this annoying bug, I might just have to ignore the xhr status of 0 in my error handling logic, which is something I would prefer to avoid.

Edit:

xhr.open("POST", "http://" + document.domain + "/script.php", true);
xhr.upload.addEventListener("progress", keepPage(file,xhr),false);
xhr.upload.addEventListener("progress", uploadProgress,false);
xhr.upload.addEventListener("load", uploadComplete, false);
xhr.upload.addEventListener("error", uploadFailed(xhr.status), false);
xhr.upload.addEventListener("abort", uploadCanceled, false);
xhr.send(fd);
var uploading = true;
uploaded = false;
xhr.onreadystatechange=function(){
    if (xhr.readyState==4 && xhr.status==200) {
        var response = xhr.responseText;
        if (response == "success"){
            var uploaded = true;
            processSuccess();
        }
        else {
            var obj = $.parseJSON(response); //parse error JSON array
            errReport = obj.errReport
            uploadFailed(errReport);
        }
     }
}
uploading_tools(file, xhr, uploaded);

Answer №1

Remember to always utilize the open() function before interacting with any other property or method of the XMLHttpRequest. Failure to do so may result in unexpected behavior.

UPDATE Upon further inspection, it appears that there is no error occurring! The issue lies within this line:

xhr.upload.addEventListener("error", uploadFailed(xhr.status), false);

You are actually not assigning uploadFailed() as the event handler for the error event. Instead, you are invoking uploadFailed(xhr.status), which means you are setting the event handler to be the return value of the function! Since uploadFailed does not return anything, there is essentially no error handler assigned. However, your function is still being called when this line is executed! Due to xhr.send() not being called yet, xhr.status is 0.

To rectify this, you need to modify the line to

xhr.upload.addEventListener("error", uploadFailed, false);

Similar to how you have set up the other event listeners:

xhr.upload.addEventListener("progress", uploadProgress,false);
xhr.upload.addEventListener("load", uploadComplete, false);

REVISED UPDATE

In response to your feedback, the issue persists because you continue to follow the same approach rather than the suggested solution. Let me try explaining it again.

Imagine your uploadFailed function looks like this:

function uploadFailed(error) {
    console.log(error);
    return true;     //let's assume this line exists, even though it's not necessary.
}

Now, let's revisit the code in question:

xhr.upload.addEventListener('error', uploadFailed(errReport), false);

What exactly is happening with this line? Essentially:

var f = uploadFailed(errReport);   //uploadFailed is being called, not assigned to f
xhr.upload.addEventListener('error', f, false); //f is not a function, but the value 'true'!

Comprehend now? When that line executes, you are executing the function and assigning the result instead of simply assigning the function itself. If passing the error value to the error function is the concern, here's a potential solution:

function uploadFailed() {
    console.log(this); //upon assigning this function as an event handler, 
                       //'this' will refer to the object triggering the event (xhr.upload)
}

You don't necessarily have to pass the xhr object to the function, but if there is a specific need to pass the error argument, you can go about it like so:

xhr.upload.addEventListener('error', function() { uploadFailed(xhr.status); }, false);

This manner, you create a new function encapsulating your xhr object in its scope, allowing you to pass it to your error function.

I trust you grasp the distinction between a function and a function call, as it holds crucial importance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Remove an option from a drop-down menu once a different option has been selected (using Jquery)

I need to remove an item (ItemX) from a dropdown menu (Drop Down 2) when ItemX is selected in Drop Down 1 using jQuery. This is how I am approaching it: <?php session_start (); ?> <!doctype html> <html lang="en"> <head> <ti ...

unveiling the comparison between the revealing module and object literal patterns in encapsulating code

When developing a new feature, my typical approach is to create a separate component for each one. For example, if I have a feature called abc, I would write the following JavaScript: var AbcComponent = (function(){} var initialize = function(){ }, ...

Modifying elements in AngularJS

Hello there! I'm fairly new to Angularjs and recently I've been working on implementing an edit feature for a field and attempting to save the data. Below is the HTML code snippet where the magic happens: <div class="row" ng-if="showme==&apos ...

A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces interface a {x:string} interface b {y:string} interface c {z:string} type all = a | b | c Now, consider an object fulfilling all by being of type c When you try to access the propert ...

Angular generates an array that is not native to the system

When I directly set vm.files in my view using the following code: <input type="file" ng-model= vm.files[0]> <input type="file" ng-model= vm.files[1]> The contents of vm.files are displayed as shown in example A: https://i.stack.imgur.com/K3V ...

Troubleshooting: MongoDB/mongoose post save hook does not execute

My current setup involves the following model/schema: const InvitationSchema = new Schema({ inviter: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true}, organisation: {type: mongoose.Schema.Types.ObjectId, ref: 'Orga ...

Using React Native to implement Firebase onSnapshot with FlatList pagination

INTRODUCTION I have a collection of items stored in FireStore with the "date" property. On the client side, I'm using a FlatList to display these items ordered by date, starting with the most recent item at the top. The challenge I'm facing is ...

Reached the maximum number of iterations for Angular 10 $digest() function

Currently, I am following a MEAN stack tutorial on Thinkster and encountering an issue with my Angular factory service. Angular.js:11598 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [] H ...

Tips on sending variables to a PHP script from a JQuery $(document).ready function

I have a chat application in development. I currently have a functioning JQuery code that calls logs.php every second to refresh the chat. $(document).ready( function(e) { $.ajaxSetup({cache:false}); setInterval(function() { ...

When the key code is equal to "enter" (13), the form will be submitted

When I press the Enter key, I want to submit a form if there are no error messages present. Here is the function I have created: $(targetFormID).submit(function (e) { var errorMessage = getErrorMessage(targetDiv); if (e.keyCode == 13 && errorMessa ...

An error occurs when trying to access the 'map' property of an undefined variable

Is there a way for me to retrieve the return value for this situation? I attempted to use forEach, but each time I try to loop through the images variable, I encounter the error ("Cannot read property 'map/forEach' of undefined") // Conso ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

Leveraging .tsx components within nested .tsx components in React Native

Currently, I am delving into the world of building apps using TypeScript in React Native. Coming from a background as a Swift developer, adjusting to JavaScript and TypeScript has been an interesting journey. An observation that stood out to me is the cha ...

The text for the Google chart is nowhere to be found

After creating a test project using the Google Chart example, I noticed that some text from the chart is missing after adding CSS. Here is the CSS code I used: html, body { font-size: 100%; height: 100%; width: 100%; } body { background: ...

Error: Unable to locate module: 'material-ui/styles/colors'

I encountered an issue with the code below, as it failed to compile: import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiThem ...

What causes the sudden disappearance of the returned value from AJAX?

This piece of code is what runs on my server: modify_emp.php <?php echo $_POST[id]; ?> Below is the Javascript code in my HTML page: <script> $(document).ready(function () { var alreadyClicked = false; $('.element').h ...

Combine the serialized form data along with an array and post them together

I am encountering difficulties with sending the form through ajax. Along with the information input by the user, I also need to include an array of objects in the data being sent. AJAX POST: submitHandler: function (form) { $.ajax({ ...

When a promise is executed, it runs the code synchronously regardless of the promise

Essentially, I have a web application that fetches data from Firebase. Due to the time it takes to retrieve this data, I've implemented promises in JavaScript to ensure my code executes at the appropriate times. Within the function getDataFirebase, in ...

A guide on utilizing the TypeScript compilerOptions --outDir feature

Recently, I encountered an error message from the compiler stating: Cannot write file 'path/file.json' because it would overwrite input file. After some investigation, most of the solutions suggested using outDir to resolve this issue. Although t ...

Pretending to determine the exact height of the body

I am facing a challenge with my JavaScript application that is loaded within an iframe through a Liferay portlet. The HTML container is currently empty and the JS is loaded only when the document is fully loaded. Upon loading the page in the iframe, Lifer ...