Dealing with AJAX error in pure JavaScript

I have been attempting to address AJAX errors using the code below, but unfortunately, it does not seem to be effective.

function ajaxPost(url, data, success, error) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status === 200) {
            if (typeof success === "function") {
                success(xmlhttp.responseText);
            }
        }else if([404, 500 , 503, 504 ].indexOf(xmlhttp.status) > -1){
            if(typeof error === "function"){
                error();    
            }
        }
    }
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xmlhttp.send(JSON.stringify(data));
}

Is there any other status code that I'm missing in [404, 500 , 503, 504 ]? I am trying to avoid unnecessary libraries and keep my code lightweight by programming everything using native JavaScript. Any assistance would be greatly appreciated.

Although the above function effectively sends data to the server, it fails to trigger an error message when the server is unreachable. Can someone guide me on how to handle this issue?

Answer №1


          // give this code a shot

          xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState === 4) {

                        var responseText=eval('('+xmlhttp.responseText+')');


                        if( xmlhttp.status == 200 ) {

                            // successful operation

                        } else if( xmlhttp.status >= 500 ) {

                            // encountering internal server error

                        } else if ( xmlhttp.status >= 402 && xmlhttp.status <= 420 ) {

                           // error occurred

                        } else if( xmlhttp.status == 400 || xmlhttp.status == 401 ) {

                           // dealing with bad request or unauthorized access error

                        }

                    }
                };

Answer №2

If you're looking to verify anything other than a successful outcome, consider this:

function ajaxPost(url, data, success, error) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status === 200) {
            if (typeof success === "function") {
                success(xmlhttp.responseText);
            }
        } else if(typeof error === "function" && (xmlhttp.status > 299 || xmlhttp.status < 200)){
            error();    
        }
    }
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xmlhttp.send(JSON.stringify(data));
}

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

Retrieve a div using Jquery Ajax

I am facing an issue with the ajax response. The .php file I have generates a table <div class="result"> <tr class="distr"> <td><input name="somename" value="value"></input</td> <td> ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

What is the reason for not modifying the filtered and sorted data?

I am currently working on implementing filter options for an item list, but I am facing an issue where the filtering does not work when selecting dropdown options. Array in App.jsx const cameraShowList=[ {id:1,model:"Canon",title:"Canon ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

Encountering an error when trying to destructure a property of null

The concept of destructuring is fascinating, but I have been facing some challenges when trying to destructure nested objects. Consider the following code snippet: const { credit: { amount }, } = userProfile This can be risky because if the &ap ...

What is the best way to create an `isHook` function in my code?

Is there a way to determine if a function passed is a React Hook? isHook(useState); // returns true isHook(() => {}); // returns false; I am looking for a method to distinguish whether a function attached to an object property is a hook or not. In cas ...

Is there a way to automatically add a div to the window as the user scrolls and then hide the div when they scroll back to the

Seeking assistance with creating a function that will add a 'sticky' class to the menu when the user scrolls down to the middle, and then append a div when the 'sticky' class is present. Currently facing issues where the div keeps appen ...

Revising Division Based on Input Number

I need to update a div every time the number input is changed. The number input looks like this: <input type="number" name="year" id="year" min="2013" value="2013"> Although I tried adding some code for this, it doesn't seem to work. Can anyo ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

How can you disable an 'option' HTML5 element using the AngularJS methodology?

How can I disable an 'option' element in HTML5 using AngularJS? Currently, I am working with AngularJS v1.2.25. Here is the Plunk Link for reference: https://plnkr.co/edit/fS1uKZ <!-- CODE BEGIN --> <!DOCTYPE html> <html> ...

Toggle checkbox feature in Bootstrap not functioning properly when placed within ng-view

When attempting to embed a bootstrap toggle checkbox within <ng-view></ng-view>, an issue arises where a regular HTML checkbox is displayed instead of the expected bootstrap toggle. Strangely, the same checkbox functions as a bootstrap toggle w ...

bespoke filter designed to conceal any negative figures

I am trying to implement a feature where a text box will display nothing if the ng-model contains a negative value. I want the ng-model to remain unchanged while ensuring that negative values are not displayed. I am looking for a custom filter to achieve t ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Does the Karma Tast Runner function on node js version 0.12.0?

I'm experiencing an issue where I have Node.js v0.12.0 installed with Karma on my OS X Yosemite, but when I try to run my test task using Gulp, it just hangs as shown in the picture. It seems like PhantomJS is not starting. Interestingly, the same cod ...

Is there a way to ensure that the elements created by the select form are only generated once?

I have a JavaScript function that dynamically creates paragraph and input elements based on user selection in HTML. However, I am looking to optimize the code so that each element is only created once. Snippet of JavaScript code: function comFunction(sel ...

What could be causing my AngularJS JSONP request to fail when trying to query Solr?

After attempting to query my Solr server with the provided code snippet: var url ="http://localhost:8080/solr/sdc/selectwt=json&callback=JSON_CALLBACK&q=opioid" $http.jsonp(url ).success(function(res){ console.log(res) }) An error is returned ...

Navigating to native script, the method for extracting an ID from a link is revealed

Is there a way to extract the unique identifier from this URL: I want to retrieve the code "11E89887FABBC1D" when clicking on the link. Any suggestions? ...

Validation message does not appear when a radio button is left unchecked

I am facing an issue with my aspx page and CS code. I have implemented two radio buttons, YES and NO, where checking YES makes a textbox visible and checking NO hides it. The problem arises when the textbox is left empty - the validation error is not trigg ...

The latest update to the Server Stats code mistakenly changes the channel to "undefined" instead of displaying the total number

I've been working on a private bot for a specific server that displays server statistics and more. However, I've encountered an issue where every time a user joins or leaves the guild, the bot updates a channel with 'undefined' instead ...

To enhance the MUI v5 table row, simply apply a border when the mouse hovers

After working on creating a table with Material UI v5, I encountered an issue where I wanted to add a blue border to the table row when the mouse pointer hovered over it. I attempted several methods and did thorough research, but unfortunately, I was unab ...