What is the method for retrieving the status of an xmlHttpRequest?

I'm curious about how to verify the status of an xmlHttp request once it has been sent. Can someone explain the process to me? Thank you.

function sendRequest(){
    //retrieve access token   
    var accessToken = 'xxx';
    //get user_id
    var userid = document.getElementById('userid').value;
    //retrieve request_token
    var requestToken = document.getElementById('requestToken').value;

     //insert into database
     var xmlHttp = new XMLHttpRequest();
     var url="database.php";
     var parameters = "accessToken=" + accessToken + "&userid=" + userid + "&requestToken=" + requestToken ;
     xmlHttp.open("POST", url, true);

    //send request
     xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlHttp.setRequestHeader("Content-length", parameters.length);
     xmlHttp.setRequestHeader("Connection", "close");
     xmlHttp.send(parameters);

    //check status
    if(xmlHttp.status == Ok){
        alert('Success!');
    }else {
        alert('Error');
    }

}

Answer №1

<!DOCTYPE html>
<html>
<body>

<h2>Utilizing the XMLHttpRequest object</h2>

<button type="button" onclick="sendRequest()">Update Content</button>

<p id="test"></p>

<script>


function sendRequest(){
    //retrieve access token
    var accessToken = 'xxx';
    //get user ID
    var userID = document.getElementById('userID').value;
    //obtain request token
    var requestToken = document.getElementById('requestToken').value;


    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("test").innerHTML =
        this.responseText;
      }
    };
   
     var url="database.php";
     var parameters = "accessToken=" + accessToken + "&userID=" + userID + "&requestToken=" + requestToken ;
     xmlHttp.open("POST", url, true);

    
     xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlHttp.setRequestHeader("Content-length", parameters.length);
     xmlHttp.setRequestHeader("Connection", "close");
     xmlHttp.send(parameters);



}

</script>

</body>
</html>

Answer №2

I believe this code snippet will solve your problem

let request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("result").innerHTML =
      this.responseText;
    }
  };
  request.open("GET", "http://example.com/api/data.php", true);
  request.send();

Answer №3

The event known as onreadystatechange is activated each time the state of readyState undergoes a change.

Throughout a server request, the readyState transitions from 0 to 4:

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

In your code, you can include a listener to monitor the onreadystatechange event and assess the status within it, demonstrated below-

function sendRequest(){
    // Obtain refresh access token   
    var accessToken = 'xxx';
    // Retrieve user_id
    var userid = document.getElementById('userid').value;
    // Acquire request_token
    var requestToken = document.getElementById('requestToken').value;

     // Insert into database
     var xmlHttp = new XMLHttpRequest();
     var url="database.php";
     var parameters = "accessToken=" + accessToken + "&userid=" + userid + "&requestToken=" + requestToken ;

     // Set up the onreadystatechange event listener.
     xmlHttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert('success');
         } else if(this.readyState == 4 && this.status != 200) { 
             alert('error');
         }
     };
     xmlHttp.open("POST", url, true);

    // Send the request
     xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlHttp.setRequestHeader("Content-length", parameters.length);
     xmlHttp.setRequestHeader("Connection", "close");
     xmlHttp.send(parameters);

    // Validate the status
    if(xmlHttp.status == Ok){
        alert('success!');
    }else {
        alert('error');
    }

}

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

Open boxes with walls that don't create shadows

Currently, I am facing an issue with an open-sided box created using MeshStandardMaterial and BoxGeometry. I have configured the box to cast and receive shadows, but it is not behaving as expected. I anticipated the interior of the box to darken when the p ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

Trigger the function when the keyboard event is deactivated

Is there a way to continuously run the top set interval whenever I lift my finger from the space key? When I try using the key up event, it only executes that function once. I'm not sure how to implement if/else logic when adding an event listener. se ...

"Presenting Invoice Information on an Invoice Template: A Step-by-Step Guide

Currently, I am working with Laravel 5.7 and VueJs 2.5.*, where I have a table of invoices. My goal is to create a new component that will display a specific invoice based on user selection, allowing them to view or print the chosen invoice. I am still ex ...

Organize the outcomes according to the date provided by the object's keys, and simply tally the number

Hello, I am struggling to retrieve a complex return using MongoDB and Javascript. Can someone please explain how to achieve this? Admin. Group the result by ID. User: Flatten the result. Here is an example of the data: let user = [ { _id: 123, ...

Developing an Easy-to-Use PDF Popup Interface

I need a simple PDF modal where I can input the text: 'The sky is blue' and have it link to a PDF that opens up when clicked. I found a similar sample online, but it includes an image plus an image modal that pops up. I want to replace the imag ...

Sending files using AJAX without FormData in Internet Explorer 9

Unfortunately, IE9 does not support FormData, making file uploads via XMLHttpRequest a more challenging task. Is there a workaround for this issue? I've come across mentions of using iFrames, but the process seems complex and unclear on how to transf ...

Create a datastring using a JSON object

When receiving data in JSON format from an AJAX call, the following code is used to parse it: var parsed=JSON.parse(data); An example output could look like this: {"confirm_type":"contract_action","job_id":12,"id":7} To generate a dynamic data string f ...

Leveraging TipTap.dev for building a joint editing platform -

I have integrated the collaboration feature from tiptap.dev into my NextJS application. Initially, I used their CLI command for the Hocuspocus server which worked well on port 1234 locally and synchronized text editing across browsers seamlessly. However, ...

Matching an element that contains a specific string in JS/CSS

I'm currently faced with an HTML file that's being generated by an outdated system, making it tricky for me to control the code generation process. The structure of the HTML code is as follows: <table cellpadding=10> <tr> ...

Angular-Google-Maps - display issues arise when adjusting map size on mobile devices

After implementing my map, I noticed that on mobile or resolutions lower than 768px, the map renders incorrectly. It seems like all the map tiles load in the top left corner and then render correctly. Even setting the resize event did not resolve this iss ...

Using Vanilla JavaScript to Disable a Specific Key Combination on a Web Page

On a completely random English-Wikipedia editing page, there exists a way to add content (for example, "test") and save it using the existing key combination of Alt+Shift+S. My goal is to specifically prevent this action without removing the save button b ...

Attempting to showcase a list of 4 concatenated items in a dropdown menu sourced from the database

I am attempting to concatenate and display 4 items in a dropdown list using AJAX. For example, the value in the dropdown list should appear as (127, CoilWt, 1, KGS) from the database. In the database, I am selecting select CODE_VALUE, CODE_DESC, CODE_SUB ...

Tips for adjusting the speed of animations in Odometer/vue-odometer

Referencing the Odometer documentation at duration: 3000, // Adjusts the expected duration of the CSS animation in the JavaScript code Even though my code is set up like this, the duration parameter doesn't seem to be effective: <IOdometer a ...

Implement rotation in Three.js that mirrors the functionality of Blender

Is there a way to permanently change the default rotation of a mesh in three.js after it has been loaded? For example, if I load a mesh with a rotation of 0,0,0, can I then rotate it 90 degrees on the X axis and set this new rotation as 0,0,0? It's i ...

Is it possible to substitute a one-line jQuery.load() with a fetch() function that achieves the same result?

I am currently working on a page where I utilize a single line of jQuery code: $('#id').load('/url'); This line allows me to load a fragment into a specific place in the DOM. However, I am now considering reducing my reliance on jQuer ...

Tips for exchanging divs in a mobile view using CSS

Illustrated below are three separate images depicting the status of my divs in desktop view, mobile view, and what I am aiming for in mobile view. 1. Current Status of Divs in Desktop View: HTML <div id="wrapper"> <div id="left-nav">rece ...

Making rapid formatting changes by rearranging the positioning of words in Javascript

Struggling to untangle my complex code, I'm unable to make the necessary adjustments. Here's what I have: var stocks= [ ["Beef (80/20) raw","oz",115.4451262,3.293742347,72,"4.85 gallons","5.65 pounds","0 - ",2.142,19,20,"0.0001275510204"," ...

Retrieve the original state of a ReactJs button from the database

I am completely new to ReactJs and I have a question regarding how to set the initial state of a button component based on data from an SQL database. I am successfully retrieving the data using PHP and JSON, but I am struggling with setting the state corre ...

Comparison between Mobile Phone's innerWidth and innerHeight Versus Resolution

My test phone, the Galaxy S3 Mini, has a resolution of 800x480 according to its specs. Strangely, when I run the following code in my HTML game: window.innerWidth window.innerHeight The width appears as 533 and the height as 295. I recently discovered ...