HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery $.ajax() Method

While methods like load() and $.post() are great for simple tasks, $.ajax() is the "master" method. It provides complete control over every aspect of an HTTP request, including timeouts, headers, specific error handling, and data formatting.


Standard Syntax

The $.ajax() method takes a single object containing all the settings for the request.

$.ajax({
    url: "test.php",      // Where to send the request
    type: "POST",         // GET or POST
    data: { id: 123 },    // Data to send
    dataType: "json",     // Type of data we expect back
    success: function(res) {
        // Runs if the request succeeds
    },
    error: function(xhr) {
        // Runs if the request fails
    }
});

Commonly Used Properties

Here are the most important settings you can use within the $.ajax() object:

Key Description
url A string containing the URL to which the request is sent.
method The type of request (e.g., "GET", "POST", "PUT", "DELETE").
data Data to be sent to the server (object or string).
dataType The type of data you expect from the server (json, xml, html, text).
timeout Set a timeout (in milliseconds) for the request.
beforeSend A function to run **before** the request is sent (e.g., show a loading spinner).

Advanced Example: Handling a Login

When handling sensitive or complex operations like a user login, $.ajax() is the best choice because it allows you to handle both success and specific server errors gracefully.

$.ajax({
    url: "login.php",
    method: "POST",
    data: $("#loginForm").serialize(),
    beforeSend: function() {
        $("#status").text("Logging in...").show();
    },
    success: function(data) {
        if(data.success) {
            window.location.href = "dashboard.php";
        } else {
            $("#status").text("Invalid credentials.").addClass("text-danger");
        }
    },
    error: function() {
        alert("Server is currently unreachable. Please try again later.");
    },
    complete: function() {
        // Always runs after success OR error
        $("#spinner").hide();
    }
});
Serialization: notice the $("#form").serialize() method. It turns an entire form's inputs into a clean string ready for AJAX transmission automatically!

Why choose $.ajax() over shorthand?

  • Security: Add custom authentication headers.
  • Reliability: Set a timeout so the app doesn't hang forever.
  • User Experience: Show and hide loaders easily using beforeSend and complete.
  • RESTful APIs: Easily use other methods like PUT and DELETE.
Pro Tip: Always use the dataType: "json" setting when communicating with modern APIs. It ensures jQuery parses the result for you so you can access response.name immediately.

Key Points to Remember

  • $.ajax() is the most powerful and flexible AJAX method.
  • It uses an object { } to define all settings.
  • serialize() is your best friend when submitting entire forms.
  • beforeSend and complete help you manage UI states (like loaders).
  • Most professional developers use $.ajax() for all their needs to ensure consistency.