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

Displaying errors above the table. Executing ng-repeat in AngularJS

I've been struggling with a seemingly simple issue for hours now. I have a table displaying equipment rows using ng-repeat and input controls, and I want to display validation errors above the table. Here's what I tried: <div class="col-xs- ...

Ways to remove the address bar from a mobile browser like Chrome or an Android browser

Is there a way to make videojs go full screen on Android devices when the URL is entered, without displaying the address bar? ...

The React Material Component stubbornly resists being horizontally aligned in the Code Sandbox

Currently, I am working on getting my Material design to function properly within the CodeSandbox environment. One issue I am encountering is attempting to center it horizontally. As of now, it appears like this: To make it easier to identify its locati ...

Best practice for setting up components in Angular 2 using HTML

I have developed a component that relies on external parameters to determine its properties: import { Component, Input } from '@angular/core'; import { NavController } from 'ionic-angular'; /* Info card for displaying informatio ...

Error: Trying to send FormData to ajax results in an Illegal Invocation TypeError being thrown

Successfully sending a file to the server for processing using the code below: var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); // {"key": "value"} $.ajax({ ...

Only scroll the div if it is not within the visible window

I've been looking at this snippet: The sidebar division is what I'm focusing on right now. I want the div to scroll along as I scroll down the page, but I need it to stop scrolling when its bottom is in view. The same should apply when scrollin ...

Is Selenium suitable for testing single page JavaScript applications?

As a newcomer to UI testing, I'm wondering if Selenium is capable of handling UI testing for single-page JavaScript applications. These apps involve async AJAX/Web Socket requests and have already been tested on the service end points, but now I need ...

Scroll bar in Highstock does not completely cover the entire length when dealing with multiple series

Having trouble with the scrollbar on a multi-series line chart where the x-axis represents dates. It seems that the maximum length of the scrollbar is determined by the length of the first, older series. When clicking the 'All' button in the ran ...

Experiencing challenges with showcasing numerical values in the grid cells

My latest project involves creating an interactive sudoku solver. I've successfully created a grid made up of various elements to resemble an empty sudoku grid. However, my challenge lies in getting the numbers to display within the grid cells. Click ...

Is using parameterized routes in Node.js a recommended practice or a mistake?

Here is the code snippet I'm working on: router.delete('/delete-:object', function(req, res) { var query; var id = req.body.id; switch (req.params.object) { case 'news' : query = queries['news_del ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

Express Validator: The Art of Isolating Validation Logic

This query is more focused on structuring code rather than troubleshooting bugs or errors. I am currently tackling request body validation, where the JSON structure looks like this: { "title": "Beetlejuice", "year&qu ...

Generating pop-up upon loading with CSS3

I have searched through numerous threads and forums in the hopes of finding a solution, but I haven't been successful. My issue lies with triggering a popup on my website. I followed online tutorials to create a popup window, which I was able to do su ...

Call getElementById upon the successful completion of an AJAX request

In the process of constructing a mini quiz, I am utilizing a variable quizScore to store the score. Each question in the quiz is displayed using AJAX. An individual AJAX call captures the ID of the button pressed (for example, on question 2, the button ID ...

Is it possible to use nodemailer locally with NodeJS? The issue is that the greeting emails are not being received

Every time I attempt to send an email using nodemailer within my local network, I encounter the following error: *Greeting never received at SMTPConnection._formatError (C:\Users\PI_TEAM\Desktop\node_modules\nodemailer\lib ...

The noclose feature in Twitter Bootstrap is malfunctioning when placed within a div

I have a PHP page named a.php that contains the following code: <ul class="dropdown-menu noclose"> This code functions correctly, preventing the drop-down menu from closing until the user clicks outside the box. However, when I load the entire a.p ...

alter objective response

Currently, I am in the process of developing an educational game for children inspired by the classic "whack-a-mole" style. In this game, kids are presented with a math question and must click on the correct number that appears to solve it. For instance, i ...

Offering various language options on a website determined by the URL

I've been contemplating how to add multi-language support to my personal website, which I developed using ExpressJS and NodeJS with EJS as the template engine. Currently, the website is only available in English, but I want to add a German version as ...

Can HTML5 be used to store IDs in PHP chat applications?

I'm in the process of developing a chat application with PHP. Everything is functioning properly, but I have encountered a potential loophole. I am implementing AJAX to fetch chat data as the user scrolls, similar to platforms like Facebook and Twitte ...

The generated hook in vuejs is throwing an error stating that window/localstorage is not defined

My goal is to save an authenticated user to local storage and then load them into Vuex on the next page load. created () { let user = window.localStorage.getItem('user') if(user) { this.setUser(JSON.parse(user)) } } I initia ...