XMLHttpRequest problem: receiving status code 0 from both local and live server

I'm struggling to make this XMLHttpRequest work correctly. This is my first time using AJAX, so I'm not sure if I've formatted everything properly. I've searched all over the internet and found similar information and examples, but certain elements are in different orders, so I'm not sure which one is correct. I've tried them all, but nothing seems to work. Here's my code:


function ajaxRequest(){
    var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
    if (window.XMLHttpRequest){
        return new XMLHttpRequest();
    }
    else if (window.ActiveXObject){ 
        for (var i=0; i<activexmodes.length; i++){
            try{
                return new ActiveXObject(activexmodes[i]);
            }
            catch(e){
                //suppress error
            }
        }
    }
    else{
        return false;
    }
}
function getData(fileName){
    var fileLoc = encodeURI("assets/"+fileName+".html");
    alert(fileLoc);
    var request = new ajaxRequest();
    request.open("GET", fileLoc, true);
    var response = request.responseText;
    alert(request.status);
    alert(response);
    request.send(null);
    return response;
}
function home() {
    var data = getData("home");
    var contentDiv = document.getElementByClassName(content);
    contentDiv.innerHTML = data;
}

home is triggered when the user clicks on a div in the page. I know that getData is being accessed because the alerts pop up, however I get a status code of 0. This happened on both my local machine and on a live server. I read that localhosts can throw a 0 status regardless of the actual status but it's happening on a live server as well. If someone could help me fix this issue and/or clarify the correct order of events in the function, I would greatly appreciate it.

EDIT: new code:


function getData(fileName){
    fileLoc = encodeURI("assets/"+fileName+".html");
    alert(fileLoc);
    request.onreadystatechange = processData;
    request.open("GET", fileLoc, false);
    request.send();
    alert(request.readyState);
    alert(response);
}
function processData(){
    if (request.readyState == 4){
        if (request.status == 200){
            document.getElementsByClassName('content').innerHTML = request.responseText;
        }
        else{
            alert("An error has occurred making the request");
        }
    }
}

Answer №1

When you instruct XMLHTTPRequest to send the request asynchronously, it means that your script will continue to execute while waiting for a response. This may result in receiving a response code of 0 (uninitialized) and an empty response, as by the time you return from the function, that is the current status and response.

Alternatively, you can define a function to be called when the state changes, or switch to synchronous mode for XMLHTTPRequest.

For more guidance, check out this tutorial which provides a simple example to assist you further.

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

It seems that in Laravel 5.3, it's challenging to add a script to a view for an autocomplete

Currently, I am working with Laravel 5.3 for my internship. However, I have encountered a frustrating issue that I need help with: I am trying to implement an "autocomplete" field on a page, but it doesn't seem to be functioning correctly. The error ...

Switch out the icons within a return statement in JavaScript

Help! I have 5 empty star icons (<StarBorderIcon/>) displayed for a product on the material-ui website. I need to replace them with filled star icons (<StarIcon/>) based on the rating entered into a function. I attempted to use replace(), but i ...

How do I ensure that in Vue.js, the select element always has the first option selected even when other options are dynamically shown or hidden?

In my Vue app, I have a select element that dynamically shows or hides options based on the user's previous selections. For example: <select id='animal' v-model='values.animal.selected'> <option value='cat' ...

Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic: $request->validate([ 'firstname' => 'required', 'lastname' => 'required', 'username' => 'required|unique:us ...

I'm having trouble locating the source of the popstate loop that is generating numerous history entries

I am currently working on a project to create a dynamic webpage where the content of the main div gets replaced when certain navigation links are clicked. I have successfully implemented the pushstate function to update the div content and change the URL a ...

Manage the angularJS user interface switch through an external event

I have implemented an AngularJS Material UI switch and I am looking to update its status based on an external event. This event occurs when a MQTT message is received on a specific topic that is published. To achieve this, I am utilizing a Node.js MQTT cli ...

What could be causing the issue with resizing windows when using a modal?

My modal contains a slider, but it doesn't show up on the screen when the modal is displayed. Interestingly, if I manually resize the window, the slider appears. I looked into this issue and found that others have mentioned it's related to the mo ...

Avoiding the default action to submit AJAX form data won't result in any changes to the front end?

Currently, I am working with Flask and have utilized JavaScript to prevent default behavior in order to send all the necessary data through an AJAX request. However, I am facing an issue where although my view contains all the data (verified by console out ...

Making all requests server-side in Next.JS: A step-by-step guide

I am in the process of creating a Next.JS application that will be retrieving data from both a Python API and a Postgres Database. Although this task may seem straightforward, the project requirements dictate that all requests must originate from the serv ...

Tips on utilizing jQuery or JavaScript to efficiently filter out outcomes exceeding a specified range

<input type="range" name="rangeInput" min="100000" max="750000" onchange="updateTextInput(this.value);"> Displayed above is the slider code that provides a value output below. <div id="sliderValue"> <p>Max Value £</p> <input t ...

What is the method to load only specific element contents using .load() rather than the entire web page?

I have a web page that allows users to add, edit, and update different sections. These segments are stored on an external page, and I use the jquery .load() function to achieve this functionality. However, I am facing some concerns regarding this process: ...

Would you say the time complexity of this function is O(N) or O(N^2)?

I am currently analyzing the time complexity of a particular function. This function takes a string as input, reverses the order of words in the string, and then reverses the order of letters within each word. For example: “the sky is blue” => ...

Sending multiple arrays to a php file using JQuery ajax

I have implemented a functionality where I am sending multiple arrays to a PHP file using AJAX. The code below shows how it's done: function call_ajax(){ var category=new Array(); $('.a:checked').each(function(i){ c ...

Error occurred while attempting to run 'postMessage' on the 'Window' object within GoogleTagManager

Recently, I encountered an error stating "postMessage couldn't be cloned". This issue seems to be affecting most of the latest browsers such as Chrome 68, Firefox 61.0, IE11, and Edge. Error message: Failed to execute 'postMessage' on &ap ...

Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this: { shape:[ 'SphereGeometry', [7, 16, 16] ] } My goal is to load a model using the following code: new THREE[shape[0]].apply( this, shape[1] ) However, it seems that using "new" and " ...

Using the outer ng-repeat's object property to filter nested ng-repeat items

I'm currently working on nesting two ng-repeats with two separate JSON files. The goal is to filter the second ng-repeat based on parameters from the first ng-repeat. The first JSON file, $scope.matches, includes information about each match in the W ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

Stop the print dialog box from causing the page to refresh

I have implemented a print button for an invoice: </script> <!--Function for printing invoice--> <script> function printpage() { window.print() } </script> <button id="print" name="print" class="btn btn-info" onClick="pri ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...

Resolve React Issue: Using Functions as React Children is Invalid

As I follow along with a React tutorial, I encountered an error while adding a POST request: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than ...