1. Home
image

jQuery Tutorial Concepts - From Beginner to Pro

Learn jQuery from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 19
  • 3
right-top-arrow
2

jQuery Ajax

Updated on 13/08/2024332 Views

Whether you know it or not, you are using Ajax regularly. Wondering how? Well, the social media platforms that you use incorporate Ajax. When you like or comment on a post and the updates happen seamlessly without interrupting your browsing experience, Ajax is at play. The eCommerce website, where you browse through products, add them to your cart, and update your cart without having to refresh the page, is also powered by Ajax. 

AJAX, short for Asynchronous JavaScript and XML, is the technology that enables these dynamic and interactive web features. When combined with jQuery, a fast and lightweight JavaScript library, AJAX becomes even more powerful and more accessible to implement. In this tutorial, we will discuss jQuery AJAX Call, focusing on using jQuery AJAX to create powerful and responsive web applications.

Overview

Google played a significant role in popularizing AJAX techniques with the launch of Gmail in 2004 and Google Maps in 2005, showing how asynchronous requests create a more desktop-like user experience within web browsers. This all-in-one tutorial will help you understand how to call Ajax in the jQuery function. We will also walk you through some examples to understand this topic better.

What is AJAX?

AJAX is used to create asynchronous web applications. It enables web pages to update dynamically by exchanging small amounts of data with the server without reloading the entire page, resulting in a smoother and more interactive user experience.

Why AJAX?

AJAX revolutionized web development by allowing developers to build web applications that feel more like desktop applications. Instead of the traditional request-response model, where each user action triggers a full page reload, AJAX enables partial updates, reducing bandwidth usage and improving responsiveness.

Introduction to jQuery AJAX

Why jQuery AJAX?

While AJAX can be implemented using native JavaScript, jQuery simplifies the process with its AJAX methods. jQuery abstracts away the complexities of handling XMLHttpRequest objects and provides a cleaner, more intuitive API for making AJAX requests. In the next section, we will talk about the AJAX method in jQuery

Setting Up jQuery

Before diving into jQuery AJAX, ensure you have jQuery included in your HTML file. You can download jQuery and include it locally or use a CDN (Content Delivery Network) to include it in your project. Here is how to include jQuery using a CDN:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>jQuery AJAX Tutorial</title>

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

</head>

<body>

    <!-- Your HTML content here -->

    <h1>jQuery AJAX Tutorial</h1>

</body>

</html>

Basic Syntax of jQuery AJAX:

The basic AJAX syntax involves calling a jQuery method ($.ajax(), $.get(), $.post(), etc.) and passing an options object with various settings for the AJAX request. Here is the generic jQuery AJAX example:

$.ajax({

  url: 'your-url-here',

  method: 'GET', // HTTP method (GET, POST, PUT, DELETE, etc.)

  data: {}, // Data to be sent to the server (if any)

  dataType: 'json', // Expected data type from the server (json, xml, html, text, etc.)

  success: function(response) {

    // Callback function for handling successful response

  },

  error: function(xhr, status, error) {

    // Callback function for handling errors

  }

});

Parameters of jQuery AJAX:

Let us break down the parameters used in the jQuery AJAX method:

  • url: The URL to which the AJAX request will be sent.
  • method: The HTTP request method (GET, POST, PUT, DELETE, etc.).
  • data: The data to be sent to the server. It can be an object, a string, or query parameters.
  • dataType: The expected data type of the response from the server (json, xml, html, text, etc.).
  • success: A callback function to handle a successful response from the server.
  • error: A callback function to handle errors that occur during the AJAX request.

Parameter

Description

Type

Example

url

Specifies the URL to which the AJAX request will be sent.

String

url: 'https://example.com/api'

method

Specifies the HTTP request method to be used (e.g., GET, POST, PUT, DELETE, etc.).

String

method: 'POST'

data

Specifies the data to be sent to the server with the AJAX request.

Object, String, Array

data: { key1: 'value1', key2: 'value2' }

dataType

Specifies the expected data type of the response from the server (e.g., json, xml, html, text, etc.).

String

dataType: 'json'

contentType

Specifies the Content-Type header of the request.

String

contentType: 'application/json'

headers

Specifies additional HTTP headers to be sent with the request.

Object

headers: { 'Authorization': 'Bearer <token>' }

timeout

Specifies the number of milliseconds after which the request will timeout if no response is received.

Number

timeout: 5000 (5 seconds)

async

Specifies whether the request should be asynchronous or not.

Boolean

async: false (synchronous request)

cache

Specifies whether the browser should cache the response.

Boolean

cache: false

crossDomain

Specifies whether the request is a cross-origin request.

Boolean

crossDomain: true

jsonp

Specifies whether to use JSONP for cross-origin requests. Only applicable when dataType is 'jsonp'.

String or Boolean

jsonp: 'callback'

jsonpCallback

Specifies the name of the JSONP callback function. Only applicable when dataType is 'jsonp'.

String

jsonpCallback: 'myCallback'

beforeSend

A pre-request callback function that can be used to modify the request headers before the request is sent.

Function

beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Bearer <token>'); }

success

A callback function to be executed when the request is successful.

Function

success: function(response) { console.log('Success:', response); }

error

A callback function to execute when the request fails.

Function

error: function(xhr, status, error) { console.error('Error:', status, error); }

complete

A callback function to execute when the request completes, regardless of whether it was successful or failed.

Function

complete: function(xhr, status) { console.log('Request completed:', status); }

AJAX Success Function

The success function in jQuery AJAX is a callback function that is executed when the AJAX request is completed. It typically receives the data returned by the server as its argument, allowing you to handle and process the response accordingly. Here is a detailed explanation of the jQuery AJAX success function:

success: function(responseData, textStatus, jqXHR) {

    // Code to handle successful response

}

Parameters:

  • responseData: The data returned by the server in response to the AJAX request. It could be in various formats like JSON, XML, HTML, or plain text, depending on the dataType parameter specified in the AJAX settings.
  • textStatus: A string indicating the status of the request. Possible values are "success", "notmodified", "nocontent", "timeout", "error", "abort", or "parsererror".
  • jqXHR: The jQuery XMLHttpRequest object that represents the AJAX request. It provides additional methods and properties for interacting with the request and response.

$.ajax({

    url: 'https://api.example.com/data',

    method: 'GET',

    dataType: 'json',

    success: function(responseData, textStatus, jqXHR) {

        // Handle successful response

        console.log('Response data:', responseData);

        console.log('Status:', textStatus);

    },

    error: function(jqXHR, textStatus, errorThrown) {

        // Handle error

        console.error('AJAX Error:', textStatus, errorThrown);

    }

});

Note:

It's important to handle errors properly in the error callback function, especially when dealing with AJAX requests, to provide a better user experience and debug potential issues.

The success function is only executed if the server responds with a success status code (e.g., 200 OK). If the server returns an error status code (e.g., 404 Not Found), the error function will be invoked instead.

AJAX Call in jQuery

AJAX call in jQuery involves using the $.ajax() function or one of its shorthand methods like $.get(), $.post(), $.getJSON(), etc.
Here is a basic example of how you can make an AJAX call using jQuery:

$.ajax({

  url: 'your_url_here',

  method: 'GET', // or 'POST', 'PUT', etc. depending on your request type

  data: { // optional data to send to the server

    param1: 'value1',

    param2: 'value2'

  },

  success: function(response) {

    // handle successful response here

    console.log(response);

  },

  error: function(xhr, status, error) {

    // handle error here

    console.error(xhr.responseText);

  }

});

This was a basic jQuery AJAX call example

Making AJAX Requests

GET Request

You can use the $.ajax() method to make a GET request using jQuery AJAX.
Here is a basic example:

$.ajax({

    url: 'https://api.example.com/data',

    method: 'GET',

    success: function(response) {

        console.log('Data retrieved successfully:', response);

    },

    error: function(xhr, status, error) {

        console.error('Error:', error);

    }

});

In this example:

  • url: Specifies the URL to which the request is sent.
  • method: Specifies the HTTP method (GET, POST, etc.).
  • success: Callback function to be executed if the request succeeds.
  • error: Callback function to be executed if the request fails.

jQuery AJAX POST Example

Making a POST request is similar to a GET request, but you specify additional parameters such as data to be sent to the server.
Here is an example of jQuery AJAX POST Example:

$.ajax({

    url: 'https://api.example.com/save',

    method: 'POST',

    data: { name: 'John', age: 30 },

    success: function(response) {

        console.log('Data saved successfully:', response);

    },

    error: function(xhr, status, error) {

        console.error('Error:', error);

    }

});

In this example, the data parameter sends JSON data to the server.

Handling AJAX Responses

Handling JSON Data

JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for sending data between a client and a server. jQuery automatically parses JSON responses into JavaScript objects. Here is how you can handle JSON data:

$.ajax({

    url: 'https://api.example.com/data.json',

    method: 'GET',

    success: function(response) {

        console.log('Data retrieved successfully:', response);

        // Process JSON data here

    },

    error: function(xhr, status, error) {

        console.error('Error:', error);

    }

});

Handling XML Data

jQuery also allows you to handle XML responses by using the dataType option. Here is an example:

$.ajax({

    url: 'https://api.example.com/data.xml',

    method: 'GET',

    dataType: 'xml',

    success: function(response) {

        console.log('XML data retrieved successfully:', response);

        // Process XML data here

    },

    error: function(xhr, status, error) {

        console.error('Error:', error);

    }

});

AJAX Error Handling

It is essential to handle errors gracefully when making AJAX requests. You can use the error callback function to handle errors. Here is a generalized example:

$.ajax({

    url: 'https://api.example.com/data',

    method: 'GET',

    success: function(response) {

        console.log('Data retrieved successfully:', response);

    },

    error: function(xhr, status, error) {

        console.error('Error:', error);

    }

});

AJAX Events

jQuery provides several events that you can use to hook into the AJAX request lifecycle. Some commonly used events include beforeSend, complete, and statusCode. Here is an example:

$.ajax({

    url: 'https://api.example.com/data',

    method: 'GET',

    beforeSend: function(xhr) {

        console.log('Request is about to be sent.');

    },

    success: function(response) {

        console.log('Data retrieved successfully:', response);

    },

    complete: function(xhr, status) {

        console.log('Request completed with status:', status);

    }

});

Final Words!

By mastering jQuery AJAX, you can create seamless user experiences and enhance the interactivity of your web projects. This tutorial has covered the basics of jQuery AJAX Call, including making requests, handling responses, error handling, and using AJAX events. With this knowledge, you can start integrating AJAX into your web applications and leveraging its capabilities to create richer user experiences. 

FAQ

1. How to call AJAX in jQuery function?
To call AJAX in jQuery, use methods like $.ajax(), $.get(), or $.post().

2. Can I make AJAX requests by jQuery?
Yes, you can make AJAX requests using jQuery using its Ajax methods.

3. How to call AJAX on load in jQuery?
To call AJAX on page load in jQuery, use $(document).ready() function to execute Ajax code.

4. How to pass data in jQuery AJAX call?
To pass data in jQuery AJAX call, use the data parameter in the AJAX settings object.

5. How to call AJAX call in JS?
To make an AJAX call in vanilla JavaScript, use the XMLHttpRequest object or the newer fetch() API.

6. What is AJAX calls?
AJAX calls are asynchronous HTTP requests from the client to the server, enabling data retrieval without reloading the entire page.

7. How to call AJAX without jQuery?
To call AJAX without jQuery, utilize native JavaScript methods like XMLHttpRequest or the fetch() API.

8. How to find AJAX call?
To find AJAX calls in a web application, inspect the network tab of the browser's developer tools.

9. How to call a function in AJAX call?
To call a function in an AJAX call, you can specify it in the success or complete callback functions of the AJAX request.

image

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...