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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.