AJAX GET Request β Explanation with Example
AJAX GET Request is used to retrieve data from a server without reloading the entire web page. Itβs commonly used in web applications to fetch data dynamically and display it to the user.
 What is an AJAX GET Request?
- AJAX: Asynchronous JavaScript and XML.
 
- GET Method: Sends data appended to the URL as query parameters.
 
- Used to request data (not modify it).
 
- Data is sent to the server, and a response is returned asynchronously.
 
 Syntax (Using jQuery)
$.ajax({
  url: 'server-script.php', // URL to send the request
  type: 'GET',              // HTTP method
  data: { id: 123 },        // Parameters sent to the server
  success: function(response) {
    // Handle successful response
    console.log(response);
  },
  error: function(xhr, status, error) {
    // Handle errors
    console.error(error);
  }
});
 Real Example
Let's say you want to fetch user data by ID.
π§© HTML:
<button onclick="getUserData()">Get User Info</button>
<div id="user-info"></div>
βοΈ JavaScript:
function getUserData() {
  $.ajax({
    url: 'get-user.php',
    type: 'GET',
    data: { user_id: 5 },
    success: function(response) {
      $('#user-info').html(response);
    },
    error: function(error) {
      console.log('Error:', error);
    }
  });
}
 get-user.php (Server-side):
<?php
if (isset($_GET['user_id'])) {
    $userId = $_GET['user_id'];
    // Dummy data fetch simulation
    echo "User ID: $userId - Name: John Doe";
}
?>
 Key Notes:
type: 'GET': Specifies GET request. 
data: Sends query parameters (user_id=5). 
success: Handles the data returned from the server. 
error: Catches any issues in the request.