Checking the status of an Xmlhttp request when the URL is inaccessible, all without the use of libraries

I am currently working on testing the functionality of a given URL using Ajax. In order to achieve this, I made some modifications to the Ajax code.

function checkURLStatus()
{
var xmlhttp;
   if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
  else
  {
   // code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4)
   {
   document.getElementById("myDiv").innerHTML=xmlhttp.status;
   }
  }
   xmlhttp.open("GET","wrongurl",true);
   xmlhttp.send();
}

My goal is to have the status displayed as 404 or 503 when the URL is incorrect. However, the desired output is not achieved. Are there any suggestions to rectify this issue?

Answer №1

You can access the status code using .status and the corresponding text with .statusText.

xmlhttp.onreadystatechange=function()
  {
      if (xmlhttp.readyState == 4)
           console.log("Response Code: " + xmlhttp.status  + " - Response Text: " + xmlhttp.statusText);
  }

Answer №2

When working with the xmlhttp events, it is important to note that a response object is passed. Therefore, utilize this code snippet:

xmlhttp.onreadystatechange=function(response) {
    if (response.readyState == 4) {
        document.getElementById("targetDiv").innerHTML = response.status;
    }
}

Answer №3

Using XHR to verify the functionality of a URL may not be feasible, since the URL must originate from the same source as the initial page. It would be best to first test your solution with a local URL to ensure it is working properly.

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

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

Passing various length values in AngularJS using stateParams

I am facing an issue with passing values of different lengths to the same state: For instance <li href="#/app/list/value1"> <li href="#/app/list/value1/value2"> Within my state definition, I have the following .state('app.list', ...

Challenges with Knockout.js Virtual Elements in Different Environments

I am facing a peculiar issue where a virtual knockout template fails to bind correctly when accessed remotely, yet functions perfectly when viewed locally. You can find the problematic page here: Here is the template I am using: <ul> <!-- k ...

Data Filling and Consolidating in MongoDB

Recently, I inquired about a similar issue here: Mongoose/Mongodb Aggregate - group and average multiple fields I am attempting to utilize Model.aggregate() to determine the average rating of all posts based on date and then further categorized by specifi ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...

Issue with PHP's ng-click not functioning properly with Angular JS's dynamic HTML generation

I'm just starting out with Angular JS. I'm trying to create an ng-click event in dynamically generated HTML from PHP, here's the code snippet. var app = angular.module('pageapp',[]); angular.module('pageapp') .filter(& ...

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...

Generating a single JSON record in React Native

Need help displaying a single JSON record from an API request on the screen. const [user, setUser] = useState(); const getUserData = async () => { // {headers: {Authorization: "Basic " + base64.encode(username + ":" + passwor ...

Using array.map with Promise.all allows for concurrent execution

Currently, I am working with an array of images and attempting to apply image processing techniques using an asynchronous function. The code is functioning as expected since each image in the array contains an index field representing its position. // Res ...

What is the process for accessing a user's followers and users they are following using the new Spotify Web API?

Having just checked out the latest Spotify API documentation, I'm curious about how to access information on a user's followers and following. Is there a way to retrieve this data using the new Spotify Web API? I am looking to make requests to t ...

The attempt to install "expo-cli" with the command "npm install -g expo-cli" was unsuccessful

Encountered an issue while trying to install expo-cli for creating android applications using npm install -g expo-cli. NPM version: 7.19.1 Node version: v15.14.0 Upon running npm install -g expo-cli, the installation failed with the following error mess ...

Ensuring that an md-radio-group is a required field in Angular Material

Currently, I am working on a project using Angular Material where I need to enforce a required radio group. This means that the user must select a radio button before being able to submit the form. The form should be considered invalid if no radio button i ...

What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like thi ...

I'm experiencing an issue with my API where it is returning invalid JSON data when I make a POST request using

I have a scenario where I am making a post request to my Next.js API for updating an address. The code snippet below shows the function that handles fetching: async function handleSubmit() { const data = { deliveryAddress, landmark, pincode, district, bl ...

Currently in development is an exciting MMORPG created with Node.js, Express, and HTML. Players will have the ability to move exclusively to

I'm developing a multiplayer online role-playing game (MMORPG) using Node.js, Express, and HTML. Currently, I'm facing an issue with keyboard interactivity in my game. When I load the game, only the 'D' key seems to work, allowing the p ...

The jqGrid method is not supported on a Windows Server 2012, causing an error with the object's property

While the jq grid is working smoothly on the asp.net dev server, it encountered an error on IIS 8 (Windows Server 2012) with the message: Object doesn't support property or method 'jqGrid' JavaScript <script type="text/javascript"> ...

"Enhancing partial views in Ruby on Rails: A step-by-step guide to

Seeking a method to update the partial view product_images.html.erb using ajax My js code is $("#delete-img").click(function(e){ var checkValues = $('input[name=image_id]:checked').map(function(){ return $(this).val(); ...

JavaScript for Acrobat

I am currently creating a form in Adobe Acrobat and incorporating additional functionality using JavaScript. I have been searching for information on the control classes for the form, such as the member variables of a CheckBox, but haven't found any c ...

The jQuery mobile tap event triggers the vclick event

I have been developing a jQuery mobile application that needs to be functional on both mobile devices and PCs. To detect finger events, I am utilizing the jQuery Finger plugin (): $('body').on('tap', 'image', function(e) { ...

Refine the table by selecting rows that contain a specific value in the href attribute of the <a> tag, and display the parent row when the child row

I've been working on filtering and searching the table below based on the href value. My code successfully filters the displayed columns in the table, but it fails to work when I search for a string within the href attribute. For instance, if I searc ...