13. AJAX Methods

AJAX Methods in JavaScript

AJAX stands for Asynchronous JavaScript and XML. It is a set of web technologies used to send and receive data from a client to a server asynchronously, meaning it happens in the background and doesn't require a page reload or user interaction.

$.ajax Method

The $.ajax() method in jQuery is the underlying AJAX function that all other AJAX methods call. It allows you to create a customized AJAX request. With this method, any kind of HTTP request can be sent - GET, POST, PUT, DELETE, etc., and handle them using callbacks.

Example:

$.ajax({
  url: "/api/data",
  type: "GET",
  success: function(response) {
    console.log(response);
  },
  error: function(error) {
    console.error("Error:", error);
  }
});

$.getJSON Method

The $.getJSON() method in jQuery fetches JSON-encoded data from a server using a GET HTTP request. This is a convenient method for getting JSON data from a URL.

Example:

$.getJSON("/api/data", function(data) {
  console.log(data);
});

$.each Method

The $.each() function in jQuery is used for iterating over an array or an object's properties. It works similarly to for...in loops in JavaScript. In the case of an object, it allows access to each property name and its corresponding value.

Example:

var obj = { "name": "John", "age": 30, "city": "New York" };

$.each(obj, function(key, value) {
  console.log(key + " : " + value);
});

$.getScript Method

The $.getScript() method in jQuery loads and executes a JavaScript file using an HTTP GET request. This is useful for loading scripts dynamically.

Example:

$.getScript("/scripts/example.js", function() {
  console.log("Script loaded and executed.");
});

$.ajaxStart Method

The $.ajaxStart() method in jQuery specifies a function to run whenever an AJAX request starts. This function will run before the AJAX request is sent.

Example:

$( document ).ajaxStart(function() {
  $( "#loading" ).show();
});

$.ajaxComplete Method

The $.ajaxComplete() method in jQuery specifies a function to run when an AJAX request completes. This function will run after the AJAX request is completed, regardless of whether the request was successful or not.

Example:

$( document ).ajaxComplete(function() {
  $( "#loading" ).hide();
});

Note: The $.ajaxStart() and $.ajaxComplete() methods are asynchronous, which means they don't block the execution of the script while waiting for the server's response.

Reference

The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:

Original Note - Azerbaijani Version