jQuery Ajax

Ajax is a method od exchaning data with the server.
Based on the response we give we get the response.
It is done without reloading the page
We have two request used in ajax
  1. GET - Requests data from the server and retrieves information from the server.
  2. POST - Submits data to be processed to a specified resource. Commonly used to send data to the server.
We use load() Method in ajax which is used to perform a GET request and load the content from the file.

load() Method

Loads the file from the server and injects to the selected element Syntax $(selector).load(url, [data], [complete]);

Example

<script>
  // Using load() method for a GET request
  $("#resultContainer").load("example.txt", function(response, status, xhr) {
    if (status == "error") {
      console.error("Error loading content:", xhr.status, xhr.statusText);
    }
  });
</script>

GET and POST Method

GET and POST Methods are used to exchange data with the servers.

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Ajax Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

<div id="resultContainer">
  <!-- Content loaded using Ajax will be displayed here -->
</div>

<script>
  // Using load() method for a GET request
  $("#resultContainer").load("example.txt", function(response, status, xhr) {
    if (status == "error") {
      console.error("Error loading content:", xhr.status, xhr.statusText);
    }
  });

  // Using $.ajax() for a GET request
  $.ajax({
    url: "example.json",
    method: "GET",
    dataType: "json",
    success: function(data) {
      console.log("GET request success:", data);
    },
    error: function(xhr, status, error) {
      console.error("GET request error:", status, error);
    }
  });

  // Using $.ajax() for a POST request
  $.ajax({
    url: "submit.php",
    method: "POST",
    data: { username: "john_doe", password: "secret123" },
    dataType: "json",
    success: function(data) {
      console.log("POST request success:", data);
    },
    error: function(xhr, status, error) {
      console.error("POST request error:", status, error);
    }
  });
</script>

</body>
</html>

Quick Recap - Topics Covered

jQuery Ajax

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.

Example js

Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK

Rating


Message