Jquery ajax tutorial with example

Jquery ajax tutorial with example

Learn how to perform Jquery ajax

Hi, in this Jquery ajax tutorial you will learn how to perform an asynchronous HTTP (Ajax) request using Jquery.

This Jquery ajax tutorial is for beginners.


Jquery ajax example

In the Jquery AJAX example below we are sending a GET request to the jsonplaceholder.

The JSONPlaceholder provides fake online REST API for testing.

$.ajax({
    url:"https://jsonplaceholder.typicode.com/posts",
    method:"GET",
    success:function(data){
        console.log(data);
    },
    error:function(error){
        console.log(error);
    }
});

url:

In the URL property, you specify that where you want to send the ajax request.


method:

In the method property, you specify the request type. Basically, there are four types of request methods that are mostly used.

  • GET – is used to read data
  • POST – is used to create data
  • PUT – is used to update data
  • DELETE – is used to delete data

success:

The success property contains a function that will be invoked when the ajax request is successful.

And this function contains an argument (data). It will give you the return data.

success:function(data){
  console.log(data);// return data
}

error:

The error function will be invoked when your ajax request is unsuccessful.

And through the error argument, you will get the error information.

error:function(error){
  console.log(error);// error information
}

In the Jquery ajax there are so many properties such as async, beforeSend, etc.

Example of the beforeSend property

It will be used when you want to perform any function before sending an Ajax request.

$.ajax({
    url:"https://jsonplaceholder.typicode.com/posts",
    method:"GET",
    beforeSend:function(){
        alert('I\'m going to make an ajax request');
    },
    success:function(data){
        console.log(data);
    },
    error:function(error){
        console.log(error);
    }
});

Click here to check all of the Jquery ajax properties.


Read also:

Posts Navigation


Leave a Reply

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