← Back to Chapters

jQuery AJAX Setup

? jQuery AJAX Setup

? Quick Overview

AJAX in jQuery allows web pages to communicate with a server asynchronously without reloading the page. jQuery simplifies AJAX setup using built-in helper methods and global configuration.

? Key Concepts

  • Asynchronous HTTP requests
  • Client-server communication
  • JSON and text data exchange
  • Global AJAX configuration

? Syntax / Theory

jQuery provides the $.ajax() method for full control, along with shortcuts like $.get() and $.post().

? View Code Example
// Basic AJAX setup using jQuery
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
method: "GET",
success: function(response) {
console.log(response);
}
});

? Live Output / Explanation

The request sends a GET call to the server and logs the response without refreshing the page.

? Interactive Example

Click the button to fetch data from an external API...
? View Code Example
// Interactive AJAX call on button click
$("#loadData").click(function() {
  $("#result").text("Loading...");
  
  $.get("https://jsonplaceholder.typicode.com/posts/1", function(data) {
    $("#result").html("<strong>Title:</strong> " + data.title + 
                   "<br><br><strong>Body:</strong> " + data.body);
  }).fail(function() {
    $("#result").text("Error: Could not fetch data.");
  });
});

? Use Cases

  • Fetching data without page reload
  • Form submission
  • Live search and filters
  • Dashboard updates

✅ Tips & Best Practices

  • Always handle errors using error callbacks
  • Use JSON for structured data
  • Avoid blocking UI during requests

? Try It Yourself

  • Convert GET request to POST
  • Handle server errors gracefully
  • Load JSON and display formatted output