Typical .ajax call in jQuery


$.ajax({
    url: "https://api.example.com/data", // URL to which the request is sent
    type: "GET", // Type of HTTP request (GET, POST, PUT, DELETE)
    data: { // Data to be sent to the server
        param1: "value1",
        param2: "value2"
    },
    dataType: "json", // The type of data that you're expecting back from the server
    success: function(response) { // A function to be called if the request succeeds
        console.log(response);
    },
    error: function(jqXHR, textStatus, errorThrown) { // A function to be called if the request fails
        console.error("An error occurred: ", textStatus, errorThrown);
    },
    complete: function(jqXHR, textStatus) { // A function to be called when the request finishes (after success and error callbacks)
        console.log("Request completed: ", textStatus);
    }
});

Here’s what each part does:

  • $.ajax({ ... }): This line begins the AJAX request. The ajax function is called on the $ object, which is a reference to the jQuery library. The function takes an object as an argument, where the properties of the object represent different settings for the AJAX request.
  • url: This is the URL to which the request is sent.
  • type: This is the type of HTTP request to make, such as “GET”, “POST”, “PUT”, or “DELETE”. If this property is not set, “GET” is used by default.
  • data: This is an object containing data that will be sent to the server. The properties of the object represent the keys of the data, and the values of the properties represent the values of the data.
  • dataType: This is the type of data that you’re expecting back from the server. This can be “json”, “xml”, “script”, “html”, or “text”.
  • success: This is a function that will be called if the request succeeds. The function takes one argument, which is the response from the server.
  • error: This is a function that will be called if the request fails. The function takes three arguments: a jqXHR object, a string describing the type of error that occurred, and an optional exception object, if one occurred.
  • complete: This is a function to be called when the request finishes, regardless of whether it succeeded or failed. The function takes two arguments: a jqXHR object and a string describing the status of the request.

Remember, these are just some of the options available in a jQuery AJAX call. There are many other options and methods available, which can provide more control and flexibility over your AJAX requests. You can find more details in the jQuery AJAX documentation.