Loading webpage with Ajax and verifying status code

I'm having an issue with a code that is meant to check if a page has loaded and then alert me with a status. However, the code doesn't seem to be working properly. I would really appreciate it if someone could take a look at it and point out where I went wrong. Looking forward to your response!

var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
    var xmlHttp;
    if(window.ActiveXObject){
        try{
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

        }catch(e){
        xmlHttp = false;
        }
    }else{
    try{
        xmlHttp = new XMLHttpRequest();

        }catch(e){
        xmlHttp = false;
        }
    }
    if(!xmlHttp){
        alert("Error");
    }
    else{
    return xmlHttp;
    }

}
function process(){
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
        xmlHttp.open("GET", "djhgkjshgkjsd.com", true);
        xmlHttp.onreadystatechange = handleServerResponse;
    }
    else{
        setTimeout('process()', 1000);
    }
}

function handleServerResponse(){
    if(xmlHttp.readyState==4){
        if(xmlHttp.status==200){
            xmlResponse = xmlHttp.responseXML;
            alert("Hi..."); // This is just to test where my code fails

        }else{
            alert('Something is wrong!');
        }
    }

}

Answer №1

You seem to have multiple issues at hand.

The most prominent one is the fact that you are neglecting to use the send() function to initiate the HTTP request.

In addition, there are other concerns worth noting:

  • You are failing to call the process function
  • Instead of utilizing a readystatechange event handler, you are repeatedly polling the readyState property
  • The readystatechange handler is only assigned when the readyState is either '0' (failed) or '4' (done), rendering it ineffective
  • Your URI appears to be an absolute one, but crucial components like the scheme (e.g. http://) are missing
  • You may encounter restrictions imposed by the Same Origin Policy when attempting to access data from different domains

A refined version of your code could resemble the following snippet:

// Support for IE7 and earlier has been omitted,
// considering the obsolescence of those browsers and the superiority of standard practices;

var xmlHttp = new XMLHttpRequest();

// Caution: Cross-Origin Request attempts require server authorization 
// through CORS in order for the data access on your site to succeed
xmlHttp.open("GET", "http://example.com", true); 

xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();

function handleServerResponse() {
    // Declare a local variable for storing the response.
    // Global variables can lead to complications in event-driven programming
    var xmlResponse; 
    if (this.readyState == 4) {
        if (this.status == 200) {
            xmlResponse = this.responseXML;
            alert("Variable successfully populated");
        } else {
            alert('An error has occurred!');
        }
    }

}

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

Numerous routers available for enhancing functionality in an Ember application

Can an Ember app have multiple router.js files? By default, one router.js file will look like this: import Ember from 'ember'; import config from '../../config/environment'; var Router = Ember.Router.extend({ location: config.locat ...

What are the drawbacks of automating the process of generating charts to track time spent on webpages?

!RESOLVED! I am looking to automatically generate charts based on users and their time spent on different pages of a website. I have a file named "log.xml" where I store user information (customers), visited pages, dates, and the time they spent; once I ...

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

Can you use ng-show within ng-if in Angular?

How can I make this input only show a property is true per the ng-if? The current code looks like this: <input type="button" class="naviaBtn naviaBlue" ng-if="ppt.Globals.hasDebitCard" ng-click="alertShow = (alertShow == 2 ? -1 : 2)" value="outstandin ...

The loading of the module from was hindered due to an invalid MIME type restriction

Exploring a three.js example and encountering an issue when utilizing import within a JavaScript module. The error message displayed is: Loading module from “http://localhost:8000/build/three.module.js” was blocked because of a disallowed MIME type ( ...

The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in: <div id="toggle" class> ... rather than: <div id="toggle" class="on"> ... I've been trying to solve this issue for about 2 hours now ...

What are some strategies for improving search efficiency in arrays containing over 50,000 elements?

I am working with a large array of strings containing about 50,000 elements. export const companies = [ "000014", "000016", "000017", "000019", "000020", "000021", "000023" ...

The issue of a jQuery slider malfunctioning when using an https URL on a Wordpress website

My WowSlider is experiencing issues on the main page of my Wordpress website with https. The images in the slider are stacked statically one after another. However, when the site is accessed with http, the slider works perfectly with the expected transitio ...

Steps to prevent uib-timepicker from automatically adjusting time based on the Browser Timezone

Currently in my database, timestamps are stored in UTC format. On the frontend, I am implementing uib-timepicker for time editing and updating purposes. However, I do not want uib-timepicker to automatically convert the time from the server's timezone ...

Express npm dependency fails to start globally

I have recently reinstalled my operating system from Windows 8.1 to Windows 8.1, and I have been using npm for quite some time. Previously, it was working fine as mentioned here. After the reinstallation, I tried installing npm i -g express, but it does n ...

Is it possible to include two AJAX requests within a single function that both execute when the same submission occurs?

Having one submit button for a function necessitates the running of two ajax functions when the submit button is clicked for validation purposes. <div class="form-group btn-group"> <input type="button" class="btn btn-link" v ...

Tips for optimizing the reuse of Yup validation schemas and improving the duplication coverage on sonar scans for Yup validation files

I am currently dealing with multiple forms that have some fields in common such as name, phone number, and account number. I am utilizing Formik and have created a schema file (schema.js) for each form. Within this file, I have outlined all the schema vali ...

Find out which way the user is scrolling in your React js application

I'm struggling to determine whether the scroll event is moving up or down, and I haven't been able to find a solution yet. import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; const Nav ...

Ensuring texture consistency for scene backgrounds in three.js

I am facing an issue with adding a background to a scene using a PNG image of 2k resolution. The background appears correctly sized on PC, but on mobile devices, it looks disproportionated. Here is the code snippet I am using: var texture = THREE.ImageUti ...

The appearance of Bootstrap-Navbar is altered when viewed on a mobile device

After creating a website that was compatible with both web and mobile devices, I encountered an issue where the navbar would not collapse on my smartphone. However, when I resized the browser window to match the size of the smartphone screen, it worked per ...

Is there a specific regex pattern available to identify CSS and JavaScript links within an HTML file?

Currently, I am using a straightforward gulp task to compress my CSS and JS files. The task appends a .min extension to the names of the compacted files. Now, I want to make changes in the HTML to direct to these new compressed files, like so: Replace thi ...

Tips for managing both DOM manipulation and state changes at the same time in AngularJS

<div my-custom-directive> <button id="myButton" ng-click="handleClick(mymodel.id)"><button> </div> app.controller('myCtrl', function($scope) { $scope.handleClick = function(id) { //Perform state change here without ...

kineticjs equivalent to jquery sortable

Could someone recommend a kineticjs plugin or script that works with jquery's "sortable" function? I am trying to create a list of shapes where I can drag and drop them, and when one element moves, the other elements shift into place. ...

Is it beneficial to use both Bootstrap and ng-bootstrap together?

I have two modules in my angular website - "bootstrap" and "ng-bootstrap". Do I need both or just one? I am thinking of keeping only "ng-bootstrap" 4.0.0.0 and removing "bootstrap". Is this acceptable? What are the steps to remove "Bootstrap"? Can I simp ...

Dealing with complications in the Rails asset pipeline management

I am working on a webpage that requires real-time data to be displayed. Therefore, it necessitates continuous ajax communication post page load. similar to this, jQuery -> setInterval -> $.ajax url: "some url" success: (data, te ...