Jquery Ajax Calls

What is ajax?

AJAX stands for Asynchronous JavaScript and XML and a web development technique used to create interactive web applications. It is very easy to learn and understand if you know Java Script or Jquery.

Let's take a simple example to understand. You have an ecommerce website where you display different products to your user. User clicks on a product and you take him to a different page where you show him product related info.

Say a user browse about 50 different products. User has to go back and forth from product page to landing page of products he will be annoyed and will leave your website.

User does not want to be redirected to another page where he just need to see product description and he has to come back for new product.

Rather what if he gets to see the product info on the same page where he can see all the product. Now, he does not even have to go on different page. He can just click on a product and get to see its description.

We can achieve this functionality using ajax. Using ajax when user clicks on a product a call will be made in the background to fetch product related data and once we have the response we will append the response to the page.

Ajax responses are fast so that user may not even notice that a request is made. Ajax request happens in the background and user does not need to refresh or navigate away from the current page.

How to use ajax?

Using jquery library we can use some of the functions provided by jquery to easily create ajax requests. let's take a look at syntax for ajax methods.

$.ajax() jquery function

Jquery ajax method takes following arguments:

  • url to make a call
  • method name
  • response type
  • form data to send

Following is full syntax used for ajax method:

$.ajax({
   url: "http://www.phpcodebooster.com/sample/url", 			
   method: "POST|GET|PUT|DELETE",      // The HTTP method to use for the request
   dataType: "xml|json|script|html",   // The type of data that you're exerciseecting back 	
   data: {                             // Data to be sent to the server.
      key1: value1,
      key2: value2		
   },
   error: function() {
   
	  // A function to be called if the request fails.					
   },
   beforeSend: function() {
   	  
   	  // A function to be called if before the request is made.
   },
   success: function(response) {
	      				
   	  // A function to be called if the request succeeds.
   },
   complete: function(response) {
	      				
   	  // A function to be called when the request finishes
   }
});​

Now, that we know about basic syntax let's learn about get and post methods usage.

$.post() jquery function

To make a post request using jquery ajax method following is a simple syntax that you can use:

$.ajax({
  type: "POST",
  url: "http://www.phpcodebooster.com/",
  data: {
	  // Data to be sent to the server.
  },
  success: function(response) {
	  // A function to be called if the request succeeds.
  }
});​

jquery provides a function to shorten above syntax. You can basically replace above code with following short syntax:

$.post( "http://www.phpcodebooster.com/", function( response ) {
    // A function to be called if the request succeeds.
});​

$.get() jquery function

To make a get request using jquery ajax method following is a simple syntax that you can use:

$.ajax({
  type: "GET",
  url: "http://www.phpcodebooster.com/",
  data: {
	  // Data to be sent to the server.
  },
  success: function(response) {
	  // A function to be called if the request succeeds.
  }
});​

jquery provides a function to shorten above syntax. You can basically replace above code with following short syntax:

$.get( "http://www.phpcodebooster.com/", function( response ) {
    // A function to be called if the request succeeds.
});​

Sample Ajax Page

Let's take a look at how we can use above jquery ajax method in our html page.

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function(){
                $.get(window.location.href, function(data, status){
                    alert("Data: " + data + "\nStatus: " + status);
                });
            });
        });
    </script>
</head>
<body>
       <button>click me</button>
</body>
</html>​

In above demo page we first included cdn for jquery using script tag:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>​

What is $(document).ready function?

$(document).ready is a function provided by jquery. This is a base function that you can use to surround other jquery methods. This function is called when your html page is fully ready to perform jquery operations.

if you dont use this function sometime you may  come across a jquery error. In order for jquery to work elements should be fully loaded and must exist in the page.

$(document).ready function make sure that your element is fully loaded and exists on the page. In our demo page we use button click method surrounded with $(document).ready function.

We added a <button>click me</button> in our html page and using jquery click method we added a event. When user clicks on a button it will make an ajax requet and when a request is finished it will show an alert.

What did we learn today?

using our tutorial you learned following things today:

  • now you know what is an ajax and how to use it using jquery
  • you learned about jquery ajax method for get and post request
  • you learned about document ready function usage