getting started with ajax


When we hit a URL from our browser to load a page on the browser then in the console of browser under network tab there are multiple requests is going to the server to fetch data.

Some of then an ajax request and the other one is non-ajax.

In this article, we will majorly focus on the Ajax request.

When we have to continuously update a section of a web page without reloading the whole page then we can use Ajax (like a subsection of a page, or checking input to a form etc).


AJAX

Ajax (Asynchronous JavaScript and XML) is a web development technique to generate faster and more interactive web pages.

Ajax is mainly used by front end developers, to get data from the server by hitting on a web service.

In today’s world many programming languages like Angular, React, jQuery and many other languages provide Ajax feature. In this article, I will show you how to use  Jquery with Ajax.

To work with Ajax developer need to have knowledge of the following items:
1. Javascript or Jquery
2. DOM (Document object model)
3. CSS

Jquery: It is a javascript library to create interactive web pages. It is also used to manage DOM of web pages.

DOM:  Dom (Document object model) is used by the browser to create the web pages.

CSS: CSS is used for the design of web page like font color, font size line spacing and divides a web page into multiple sections.

All above items itself a whole concept. But here we are focusing on Jquery Ajax.

Some of the popular websites Using Ajax (almost all websites use ajax now)
Google
Gmail
Yahoo
Linkedin
Twitter
Many more….
Even every web application in today’s world is using Ajax.

Sample  code (using jquery)

$.ajax({
url:’Address of web page’,
Method:’POST/GET/PUT’,
Data:{Data that web need to send to server},
contentType:’ApplicationJson/HTML/XML’,
success:function(){
},
error:function(){},
done:function(){}
})

success()=> This function is automatically called when a successful return from the server means when Server return HTTP Status Code 200: ok
error()=> This function is automatically called when the server does not return 200 the code inside this block executes automatically.
done()=> this function executes every time either it is a success or error.

We use this function when we have to perform some task which is independent of the server response.

Here term HTTP Used
HTTP is web protocol which is used to transfer data over the internet.
There is some standard status code which is a server used to identify the status of a web request.

1. 200 OK or success code
2. 400 client side error
3. 404 client side error
4. 500 some error on the server
5. 401  client side error
6. 304 Page redirection

There are many more status codes and we can create our custom codes.

To working with Ajax we first need to include Jquery file into our Javascript file.
In the below code we are including Jquery library into script section

<!DOCTYPE html>
<html>
<head>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
</html>

Below is an example of how to use Ajax with GET  request.

In the below example are hitting a web API and getting data from the server and printing it to the browser console.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p><input type="button" onclick="GetAllData()" value="Get All data by Ajax Call"></button></p>

<input type="button" onclick="Getdatabyid()" value="Get by ID"></button></p>

</body>

<script>
var id =1
function Getdatabyid(){

var url = 'https://jsonplaceholder.typicode.com/todos/'

 $.ajax({
 url: url+id,
 type: 'GET',
 success: function(data) {
  //called when successful
 id=id+1;
  console.log(data)
 },
 error: function(e) {
  /// Error
 }
});

}

function  GetAllData(){

$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/',
type: 'GET',
success: function(data) {
//called when successful
console.log(data)
},
error: function(e) {
/// Error
}
});

}

</script>
</html>

 

When we click on get all data by ajax call following is the result.

When we click Get by ID we get the result by ID

Below is the result:

 

Nowadays every modern language providing the feature of Ajax. it is become very difficult to create a web application without ajax.

Let’s create a new Ajax call with Post Example.

function  GetAllData(){

$.ajax({
url: 'URL TO POST The Data',
type: 'POST',
data:{id:1,Name:"Test Name", Age="45"},
success: function(data) {
//called when successful
console.log(data)
},
error: function(e) {
/// Error
}
});

}

In the above example

We have changed the type from GET to POST and we are also using Data attribute which is used to send data to the server.

Types of HTTP requests
1. GET
2. POST
3. PUT
4. DELETE

All the above request type is self-explanatory, But there is always a question about the difference in POST and PUT

POST is mainly used to save data to the server and generally, there is no limit of sending data by POST.

Put is also used to send data to the server but it is generally used for update data on the server.

In the above example, we use POST Type to send data to the server.

example of using PUT.

PUT Example:

$.ajax({
type: 'PUT',
dataType: 'json', // It can be HTML/JSON/XML
url: "URL of web API"
data: '{"name": "Mike"}' // Some data e.g. Valid JSON as a string,
Success: function(data){
// do some DOM changes when we get a success from server
},
error:function(data){
// do some activity when error function call.
// like display a error message
}
});

 

  • Ajax requests play a very major role in a microservice architecture. Where data is coming from many many services which are hosted on a different server over the globe.
  • Difference Between Ajax request and HTTP Request.
  • Many times some developers are confused about ajax and HTTP.
  • HTTP (Hypertext transfer protocol) which is used to transmit data from client to server or from server to server.
  • The main point to remember about HTTP requests is they are stateless.
  • On the other hand, Ajax is request done with help of HTTP, Any Ajax data transmitted through an HTTP request.
Categories