← Back to Chapters

jQuery AJAX Core

⚡ jQuery AJAX Core

? Quick Overview

jQuery AJAX Core focuses on the practical usage of the $.ajax() method. It is used to send asynchronous HTTP requests to the server and handle responses without reloading the web page.

? Key Concepts

  • Asynchronous communication with server
  • Using $.ajax() for full control
  • Handling success, error, and completion
  • Sending data to server

? Syntax / Theory

The $.ajax() method is the most flexible and powerful AJAX method in jQuery. It allows full configuration of request type, data, response handling, and callbacks.

? View Code Example
// Basic structure of jQuery $.ajax() method
$.ajax({
url: "server.php",
type: "GET",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

? Code Example(s)

? View Code Example
// AJAX request to fetch data from server
$("#loadData").click(function() {
$.ajax({
url: "data.txt",
type: "GET",
success: function(data) {
$("#result").html(data);
}
});
});

? Live Output / Explanation

What Happens?

When the button is clicked, jQuery sends a request to the server. The response is received asynchronously and displayed on the page without refreshing it.

? Interactive Example

Response will appear here
? View Code Example
// Interactive AJAX example with button click
$("#loadData").click(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
type: "GET",
success: function(data) {
$("#result").html("<strong>Title:</strong> " + data.title);
},
error: function() {
$("#result").html("Error loading data");
}
});
});

? Use Cases

  • Loading data dynamically
  • Submitting forms without page reload
  • Fetching API data
  • Updating UI asynchronously

? Tips & Best Practices

  • Always handle errors in AJAX calls
  • Use JSON for structured data
  • Avoid unnecessary AJAX requests
  • Use beforeSend for loaders

? Try It Yourself

  • Create an AJAX call using POST method
  • Display server response in a div
  • Add a loading indicator
  • Handle error responses gracefully