In AJAX, XMLHttpRequest has several attributes and methods for performing various sorts of tasks. Among these properties and methods, the status property/attribute defines the overall state of the data request submitted by the XMLHttpRequest. Or we may say that the status code is a three-digit integer that represents the outcome of the request issued by the XMLHttpRequest object, such as whether it was successful, encountered an error, or was redirected.

Using jQuery's noConflict() Method

The syntax for the status property is –

Format

if(XMLHttpRequestObjectName.status == 200){
   // Body
}

We may use the XMLHttpRequest object to obtain a status property or attribute. If the status code is equal to 200, the code in the body will run.

Status Codes

The HTTP status codes received are listed below:

Successful

Status

Message

Description

200

OK

if the request is acceptable.

201

Created

upon completion of the request and creation of a new resource.

202

Accepted

when the server approves the request.

204

No Content

when the response body contains no data.

205

Reset Content

The browser clears the transaction form for more inputs.

206

Partial Content

The browser clears the transaction form for more inputs.

Redirection

Status

Message

Description

300

Multiple Choices

It serves as a representation of a list of links. in order for the user to click on any link and visit that destination. Only five sites are permitted.

301

Moved Permanently

when the updated URL is used for the requesting page.

302

Found

when a different URL contains the requested page.

304

Not modified

The URL has not been changed.

Client Error

Status

Message

Description

400

Bad Request

Because the request was faulty or had incorrect syntax, the server is unable to fulfill it.

401

Unauthorised

The user’s credentials are not valid, and the request requires authentication.

403

Forbidden

The server understood the request but did not fulfill it.

404

Not Found

The specified page cannot be located.

405

Method Not Allowed

The page does not support the method used to submit the request.

406

Not Acceptable

The client cannot accept the server’s answer.

408

Request Timeout

Timeout on the server

409

Conflict

The request cannot be performed because it contains a conflict.

410

Gone

The requested page is not accessible.

417

Exception Failed

The server does not meet the criteria for the Expect request header field.

Server Error

Status

Message

Description

500

Internal Server Error

When the server encounters errors while processing the request.

501

Not Implemented

When the server does not recognize the request method or is unable to fulfill the request

502

Bad Gateway

When the server functions as a gateway and retrieves an incorrect answer from another server (upstream)

503

Service Unavailable

When the server is unavailable or offline.

504

Gateway Timeout

When the server functions as a gateway and fails to obtain a timely response from the other server (upstream).

505

HTTP Version Not Supported

When the server does not support a particular HTTP protocol version.

511

Network Authentication Required

When the client has to authenticate in order to access the network.

Flow Chart

The following code retrieves data from the server. So we define a method named showDoc(). We now call this function by clicking the “Click Here” button. This method will generate a new XHR object with the XMLHttpRequest() constructor. Then it constructs a call-back method to process the request. Then it invokes the XHR object’s open() function to initialize the request with the HTTP GET method and the server’s URL. Finally, it calls send() function to send the request to the server.

So, when the server answers to the request, the “onreadystatechange” property invokes the callback method using the current state of the XMLHttpRequest object. If the status is 200, it signifies the request was successful, and the result is displayed on the screen and logged in the console. If the status code is 404, it signifies that the server detected a problem. So we received an error notice in the console log.

Example

<!DOCTYPE html>
<html>
<body>
<script>
   function ShowDoc() {
      // Creating XMLHttpRequest object
      var myhttp = new XMLHttpRequest();
   
      // Creating call back function
      myhttp.onreadystatechange = function() {
         // Checking the status of the response
         // This will proceed when the response is successful
         if (this.status == 200){
            console.log("Found the requested data")
            document.getElementById("example").innerHTML = this.responseText;
         }
         // This will proceed when the error is found
         else if(this.status == 404){
            console.log("Found error");
         }
      };
      // Open the given file
      myhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/3", true);
   
      // Sending the request to the server
      myhttp.send();
   }
</script>
<p>Please click on the button to fetch data</p>
<button type="button" onclick="ShowDoc()">Click Here</button>
<div id="example"></div>
</body>
</html>

Output

Conclusion

These are the status codes used by XMLHttpRequest. The status codes indicate the status of the request. We can process the request based on these status codes. The next article will explain how the XMLHttpRequest handles failures.

Ajax: Applications

AJAX is a popular web technology that allows you to transmit and receive data from the web server asynchronously without having to reload the entire web page. It is simple to learn and use since it combines existing web technologies such as JavaScript, XML, and HTML. It makes online applications more responsive and engaging, allowing them to receive and display data in real time without refreshing the entire site. Because of its incredible capabilities, it is employed by practically all web application developers, including small and major businesses.

AJAX is widely utilized in practically all internet-based applications. Here are some popular applications:

Google Maps: An excellent example of an AJAX application. It uses AJAX to dynamically refresh the maps and display only the desired information without reloading the entire site.

Facebook: A great example of an AJAX application. It use AJAX to refresh feeds, alerts, news, and other functions. Ajax is also used to refresh the Facebook material on a web page according on the user’s actions.

Gmail: Gmail also makes use of AJAX to give users a smooth and engaging experience. Gmail can update the inbox, remove emails, and mark emails as read without requiring a page refresh thanks to AJAX.

Twitter: Another excellent illustration of an AJAX application is Twitter. The user is given a real-time environment through the usage of AJAX. Every time a new tweet is posted, the timeline is updated without requiring a site refresh. This also applies to the notice.

Online retailers: Online retailers also utilize AJAX to display product information and current prices without forcing consumers to go to a different page.

Google: Google’s auto-complete function also makes use of AJAX. When a user types something into the Google search field, the auto-complete function takes over and offers real-time suggestions in a drop-down list without requiring the user to refresh the original site. Additionally, this property is employed in a variety of ways.

Chats and instant messages: These days, the majority of websites include customer support chat features that allow them to interact with clients without having to reload the entire page. This capability is also accomplished using AJAX.

Form submission and validation: AJAX is used by a number of websites to submit and validate forms. In some form fields, it offers an auto-filling capability. It can also make suggestions (similar to the autocomplete tool) for potential entries for the designated field. Additionally, AJAX is utilized to verify the user’s credentials.

Voting and rating systems: A number of websites employ voting and rating systems, which enable users to alter the data based on the votes and ratings. Additionally, users have the option to vote or score the material on a particular website, and the website will subsequently alter its content in response. These websites employ AJAX to handle user ratings and votes.

Conclusion

All things considered, AJAX is a highly potent approach that enables web developers to build dynamic and interactive online applications. By using this method, an application may interact asynchronously with the server without requiring a page refresh for each request. Users of dynamic applications get a seamless browser experience. Database operations will be covered in the next article.

Categorized in: