Simple asynchronous/synchronous $.ajax() example using jQuery to make an HTTP GET request

CK CK 3788 
Created at
Updated at  
850 0 0

The jQuery `$.ajax()` function is the core of asynchronous communication in jQuery. It essentially allows you to send requests to a server and receive responses, all without halting the execution of your JavaScript code. Here's a breakdown of its functional role:
1. Sending Requests:

  • HTTP Methods: It lets you use various HTTP methods (GET, POST, PUT, DELETE, etc.) to interact with server-side resources.
  • URLs: You specify the URL of the target resource you want to communicate with.
  • Data: You can send data along with your request (e.g., form data, JSON objects) using the `data` option.

2. Receiving Responses:

  • Asynchronous Nature: `$.ajax()` works asynchronously, meaning your code continues to execute while the request is being processed on the server.
  • Callbacks: You define callback functions within the `$.ajax()` call to handle different stages of the request:
    • success: This function is executed if the request was successful and the server returned a valid response.
    • error: This function is executed if there's an error during the request (e.g., a network problem or a 404 error).
    • complete: This function is executed regardless of whether the request was successful or not.

3. Processing Responses:

  • Data Extraction: The response from the server is typically received in the form of text. You can use methods like `JSON.parse()` to convert it to a JavaScript object for easier manipulation.
  • Handling Responses: The `success` callback function gives you access to the response data and allows you to update your webpage or perform other actions based on the server's response.

Essentially, `$.ajax()` bridges the gap between your JavaScript code and the server, enabling dynamic interaction and data exchange.

 

Below is a simple asynchronous $.ajax() example using jQuery to make an HTTP GET request.

Example: Asynchronous $.ajax() Call

<!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>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>jQuery $.ajax() Example</h1>
    <div id="result"></div>
    
    <script>
        // Asynchronous AJAX request
        $.ajax({
            url: 'https://jsonplaceholder.typicode.com/posts/1',  // URL to send request
            type: 'GET',  // HTTP method (GET, POST, etc.)
            dataType: 'json',  // Type of data expected from server
            success: function(response) {
                // Success callback function
                console.log(response);
                $('#result').html('<h2>' + response.title + '</h2><p>' + response.body + '</p>');
            },
            error: function(xhr, status, error) {
                // Error callback function
                console.log("Error: " + error);
                $('#result').html('<p>Something went wrong. Please try again.</p>');
            }
        });
    </script>
</body>
</html>

Explanation:

  • url: The URL where the request is sent. In this example, it's a placeholder API.
  • type: The type of HTTP request (GET, POST, etc.). Here, it's a GET request.
  • dataType: The type of data expected back from the server, in this case, JSON.
  • success: This callback is triggered when the request completes successfully. The response is passed as a parameter.
  • error: This callback is triggered if there is an error with the request (e.g., the server is down).

When you open this HTML page, it will make an asynchronous request to the JSONPlaceholder API, retrieve a sample post, and display its title and body in the <div id="result"></div>.

 

To make a synchronous $.ajax() request in jQuery, you can set the async option to false. However, it's important to note that synchronous requests are deprecated because they block the browser while waiting for the response, potentially making the web page unresponsive.

Despite this, here's how you can make a synchronous request:

Example: Synchronous $.ajax() Call

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Sync Ajax Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>jQuery Synchronous $.ajax() Example</h1>
    <div id="result"></div>
    
    <script>
        // Synchronous AJAX request
        $.ajax({
            url: 'https://jsonplaceholder.typicode.com/posts/1',  // URL to send request
            type: 'GET',  // HTTP method (GET, POST, etc.)
            dataType: 'json',  // Type of data expected from server
            async: false,  // Setting this to false makes the request synchronous
            success: function(response) {
                // Success callback function
                console.log(response);
                $('#result').html('<h2>' + response.title + '</h2><p>' + response.body + '</p>');
            },
            error: function(xhr, status, error) {
                // Error callback function
                console.log("Error: " + error);
                $('#result').html('<p>Something went wrong. Please try again.</p>');
            }
        });
        
        // Code execution will be blocked here until the AJAX request is completed
        alert('AJAX request finished.');
    </script>
</body>
</html>

Key Differences:

  • async: false: This makes the AJAX request synchronous, meaning the browser will wait for the request to complete before executing any further JavaScript code.
  • Blocking: Any code after the $.ajax() call will not run until the AJAX request finishes, which can lead to a poor user experience.

Warning:

  • Deprecated: Synchronous AJAX calls (async: false) have been deprecated and are generally discouraged because they block the user interface, making the page unresponsive.
  • Modern Practice: It's better to use asynchronous requests with promises or async/await (if you're using vanilla JavaScript or modern frameworks).
     
Tags AJAX Example Async: false Asynchronous AJAX Blocking AJAX Error Callback HTTP GET Request JSONPlaceholder API Success Callback Synchronous AJAX jQuery jQuery $.ajax() Facebook X
Comments 0
Similar posts
  1. jQuery and Function Chaining
    538
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Tailwind CSS and shadcn/ui for React App with Charts and Graphs
    1,043
  3. HTML NoIndex: Keep Pages Off Search
    1,495
  4. JavaScript to disable Screen Saver or Power Saving Mode
    501
  5. Improving SEO with image-sitemap
    1,180
  6. Making HTML Tables Responsive on Mobile: Addressing Text Overflow
    774
  7. How do we make better SEO with schema.org?
    424
  8. A Javascript code that returns Monthly Mortgage Payment and Tax
    1,254
  9. A simple JavaScript snippet to copy a string to the clipboard
    1,052
  10. Dynamic JSON Editor based in HTML/JavaScript
    511
  11. How to post content (image or video) to Instagram using the Instagram Graph API
    6,395
  12. Font name correctly having the same width space
    1,216
  13. JavaScript Algorithms
    718
  14. GraphQL Tutorial on CentOS 7: From Installation to Deployment
    558
  15. Capture all browser console logs including errors for debugging
    2,174
  16. JavaScript Code to Get Page Keywords
    347
  17. What is OpenGraph?
    366
  18. What is Twitter Cards?
    402
  19. Code to Extract the Site Thumbnail Image for Twitter or Facebook
    393
  20. JavaScript Code to Get the Page Title
    335
  21. JavaScript Code to Get Meta Description from HTML
    396
  22. Javascript code to extract favicon URL
    396
  23. RSS to Array in JavaScript
    2,154
  24. Javascript function to convert sitemap.xml to array
    599
  25. Understanding Elasticsearch from Installation to Trouble Shooting
    913
  26. IndexNow for better SEO
    318
  27. Enhancing SEO for Single Page Applications: Implementing Dynamic URL Updates
    1,041
  28. Method to ignore JavaScript Errors globally instead of try... catch for each of cases
    970
  29. Method to catch the browser console log and errors for remote web debugging
    2,173
  30. Atlassian Jira Ticket API Response Example
    2,768
Recently updated
  1. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  2. How do I create animated background for Google Meet?
    21,003
  3. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  4. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  5. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  6. Array of arguments passed to script in PHP
    90
  7. Invalid Auction Storms in Ad Tech
    98
  8. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  9. The Two Clocks of Ad Server Architecture
    70
  10. Frequency Cap Architecture Overview
    515
  11. Collecting Proof-of-Play from 100,000 Screens
    146
  12. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  13. What is RedisVL?
    109
  14. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    231
  15. TPU & GPU Cluster Management Tools
    245
  16. The Concept of Scaffolding in AI Agents
    234
  17. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  18. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  19. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  20. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  21. Machine Learning: Training vs. Ranking
    222
  22. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  23. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  24. Designing a Data Curation System Around a Vector Database
    221
  25. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  26. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  27. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  28. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  29. Understanding Data Lineage
    262
  30. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    167