Basics of Ajax – Web Development

Hey!! Friends, welcome to our new article, the basics of Ajax. Here we will start from where we finished in the previous article. 

Now, lets get the started tutorial of basics of Ajax.

If you missed the previous article then please check once events in javascript.

What is AJAX?

If you already know the HTML, CSS, JavaScript, then you need to spend just one hour on starting with AJAX. AJAX is an acronym that stands for Asynchronous  JavaScript and XML, and it describes a set of development techniques used for and web applications.

basics of ajax

According to the web developer and Skillcrush WordPress instructor Ann Cascarano, the best way to understand AJAX is to start with identifying its specific purpose in the web development process.

AJAX’s core function does update the web content asynchronously (the “A” of AJAX), meaning a user’s web browser doesn’t need to reload an entire web page. Only a small portion of the content on the page needs to change.

The AJAX is Based on Open Standards

the AJAX is based on the following open standards −

  • A browser-based presentation using HTML and Cascading Style Sheets (CSS).
  • Data is stored in XML format and fetched from the server.
  • Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
  • JavaScript to make everything happen.

XHR Request

  • XMLHttpRequest is an object that is used by all modern browsers to communicate with the server.
  • This object is commonly used in AJAX programming.
  • You can also update only a part of a web page using this object.
  • It helps in making synchronous and asynchronous calls to the server and retrieving data without a full page reload.
  • Let us see how to make synchronous calls and its disadvantages.
Syntax for creating an XMLHttpRequest object: 
variable = new XMLHttpRequest();

For Example

var request= new XMLHttpRequest();
request.open('GET','Example.txt',false);
request.send();
if(request.readyState == 4 && request.status == 200){
console.log(request);
document.writeln(request.responseText);
}
document.writeln("some text");

In this code, since we passed false as a parameter to open() function, the browser treats this as synchronous calls and wait for the server to respond and then execute the next line.

Making asynchronous request

The onreadystatechange Property

The readyState property holds the status of a XMLHttpRequest.

The onreadystatechange property is defined as a function to be executed when the readyState changes.

The status property and the statusText both properties hold the status of the XMLHttpRequest object.

PropertyDescription
onreadystatechangeIt is defined as a function to be called when the readyState property change
readyStateHolds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: suggestion finished, and the response is ready
status200: “OK.”
403: “Forbidden.”
404: “Page not found.”
statusTextit is returned the status-text (e.g., “OK” or “Not Found”)

The onreadystatechange the function of javaScript is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

For Example:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send(); }  

Updating the DOM in basics of Ajax

basics of ajax

By using the response from the server, you can update the DOM. One way of doing that is by using getElementById. Consider the same example from the previous card

<body>
<p id="myElement"></p>
<script>
var request= new XMLHttpRequest();
request.open('GET','example.txt',true);
request.send();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200){
console.log(request);
document.getElementById("myElement").innerHTML =request.responseText;
}
};
</script>
</body>

Here the javascript will find the element with the required id and replace it with the response from the server. This can also be done using getElementByTagName which you should be familiar with previous topics.

Parsing XML with AJAX

The XMLHttpRequest Object is Configured

Here, we will write a function that will be triggered by the customer(client) event, and a callback function processRequest() will be registered.

function validateUserId() {
   ajaxFunction();
   
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatechange = processRequest;
   
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);
}

Webserver Returns the Result Containing XML Document

We can implement your server-side script in any language. However, its logic should be as follows.

  • Get a request from the client.
  • Parse the input from the client.
  • Do the required processing.
  • Send the output to the client.

If we assume that you are going to write a servlet, then here is the piece of code.

public void doGet(HttpServletRequest request,
   HttpServletResponse response) throws IOException, ServletException {
   String targetId = request.getParameter("id");
   
   if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("<valid>true</valid>");
   } else {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("<valid>false</valid>");
   }
}

Some Different ways to do Ajax calls in JavaScript

XHR

XMLHttpRequest is an object such as (a native component in most other browsers, an ActiveX object in Microsoft Internet Explorer) that permits a web page to make a request to a server and get a response back without reloading the entire page. The user continues on the same page that is page did not fill, and more importantly, they will not actually see or notice the processing occur — that is, they will not see a new page loading, not by default, at least.

Performing GET request using XHR

axios.get('/get-user', {
    params: {
      ID: 1
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Request

The Request library is one of the easiest ways to make HTTP calls. The structure and syntax are very similar to that of how requests are handled in Node.js. Currently, the project has 18K stars on GitHub and deserves mention for being one of the popular HTTP libraries available.

Syntax

axios.get('/get-user', {
    params: {
      ID: 1
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Axios

Axios is one among many available promise-based HTTP clients that work both in the browser and in a node.js environment. Basically, it provides a single API for dealing with XMLHttpRequest s and node’s HTTP interface. Apart from that, it binds the requests using a polyfill for ES6 new’s promise syntax.

Performing GET Request in Axios

axios.get('/get-user', {
    params: {
      ID: 1
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

FAQs:

AJAX requests can support the data transfer in ______ format.

Ans: any type of format, we can use in the data transfer.

________ object uses to make calls and request data from the server.

Ans: The XMLHttpRequest object can be used to request data from a web server.

Is the data from the AJAX request usually in XML? State if the statement is true or false?

Ans: this statement is false

What are the advantages of AJAX?

Ans:1) Quick Response
2) Bandwidth utilization
3) The user will not be blocked until data is regained from the server.
4) Ajax allows us to send only necessary data to the server.
5) With the help of Ajax, the application interactive and faster.

What is the real web application of AJAX in the present time running in the market?

Ans: there are many web applications:-
1) Twitter
2) Facebook
3) Gmail
4) Javatpoint
5) Youtube

In this article, we see the basics of Ajax, which is a vital part of Web Development. After this, we will discuss the basics of JSON.

Thanking you for reading this article and feel free to contact us for any concerns 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *