jquery
  1. jquery-ajax-introduction

Introduction to jQuery AJAX

jQuery AJAX is a powerful tool that allows you to load and send data to a server without reloading the page. It makes it easy to develop dynamic and interactive web applications that can communicate with web servers in real-time.

Syntax

The basic syntax for making an AJAX call with jQuery is:

$.ajax({
  url: "example.php",
  success: function(data) {
    // code to handle successful response
  },
  error: function() {
    // code to handle error response
  }
});

This example shows how to make a call to example.php and handle the response using success and error functions.

Use

jQuery AJAX is used for a variety of purposes such as loading data from a server, sending data to a server, updating parts of a web page without reloading the entire page, and performing form submissions in the background.

Example

Here is an example of how to use jQuery AJAX to load data from a server and update a part of the page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery AJAX Example</title>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

    <div id="result"></div>

    <script>
        // Use $(document).ready() to ensure the DOM is fully loaded before executing the script
        $(document).ready(function() {
            // Make a GET request using jQuery AJAX
            $.ajax({
                url: 'https://jsonplaceholder.typicode.com/todos/1',
                method: 'GET',
                dataType: 'json',
                success: function(data) {
                    // Handle the successful response
                    console.log('Success:', data);
                    $('#result').html('Title: ' + data.title);
                },
                error: function(xhr, status, error) {
                    // Handle errors
                    console.error('AJAX request failed: ', status, error);
                }
            });
        });
    </script>
</body>
</html>
Try Playground

In this example, we use the $(document).ready() function to ensure the page is fully loaded before making an AJAX call. When the user clicks the #load-data button, AJAX loads the contents of data.txt and updates the content of the #data-container element.

Summary

jQuery AJAX is a powerful tool that allows you to create dynamic and interactive web applications that can communicate with web servers in real-time. With its easy to understand syntax and versatile capabilities, AJAX can help you take your website or web application to the next level.

Published on: