jQuery AJAX
What is AJAX?
AJAX (Asynchronous JavaScript and XML) is a technique used to send and receive data from a server without reloading the webpage.
Why Use jQuery AJAX?
✅ Faster and smoother user experience – No need to refresh the page.
✅ Sends and retrieves data dynamically – Get data from a server without delays.
✅ Shorter, cleaner code – jQuery makes AJAX easier to use than plain JavaScript.
jQuery AJAX Methods
Method | Description |
---|---|
$.ajax() | The main method for making AJAX requests. |
$.get() | Sends a GET request to retrieve data. |
$.post() | Sends a POST request to submit data. |
$.getJSON() | Retrieves JSON-formatted data. |
load() | Loads content from a server response into an element. |
📌 GET vs. POST
• GET – Used for retrieving data (safe, cacheable, limited data).
• POST – Used for sending data (secure, larger data, no caching).
1. Load Data into an Element – load()
The load() method fetches content from a file or server and places it into an element.
👉 Example: Load content from “data.html” into a <div>.
📌 index.html File
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Load Content Using jQuery</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#contentBox {
width: 50%;
padding: 10px;
border: 1px solid black;
margin-top: 10px;
}
button {
padding: 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button id=”loadBtn”>Load Content</button>
<div id=”contentBox”> Content load here…</div>
<script>
$(document).ready(function() {
$(“#loadBtn”).click(function() {
$(“#contentBox”).load(“data.html”);
});
});
</script>
</body>
</html>
📌 data.html File
<h2>Data Loaded Successfully!</h2>
<p>This content loads from the data.html file.</p>
📌 Output
📌 How It Works?
1️⃣ Button Click: When the “Load Content” button is clicked, the content from data.html is loaded into #contentBox.
2️⃣ jQuery .load() Method: $(“#contentBox”).load(“data.html”);
This sends an AJAX request to fetch content from data.html and inserts it into the #contentBox div.
2. Get Data from a Server – $.get()
The $.get() method retrieves data from a server using a GET request.
👉 Example: Get text data from “data.txt” and display it in a <p>.
📌 index.html File
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Load Text File Using jQuery</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#contentBox {
width: 50%;
padding: 10px;
border: 1px solid black;
margin-top: 10px;
}
button {
padding: 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button id=”getBtn”>Get Data</button>
<div id=”contentBox”>Text file content will be loaded here…</div>
<script>
$(document).ready(function() {
$(“#getBtn”).click(function() {
$.get(“data.txt”, function(data) {
$(“#contentBox”).text(data); // Displays text file content
});
});
});
</script>
</body>
</html>
📌 data.txt File
This is some text from the data.txt file.
📌 Output
📌 How It Works?
1️⃣ Button Click: When the “Get Data” button is clicked, jQuery sends a .get() request to fetch data.txt.
2️⃣ jQuery .get() Method:
– $.get(“data.txt”, function(data) {…});
– Retrieves the content of data.txt and passes it to the function.
3️⃣ Displaying Data:
– $(“#contentBox”).text(data);
– The fetched text is inserted inside the #contentBox div.
3. Send Data to a Server – $.post()
The $.post() method sends data to a server using a POST request.
👉 Example: Send a name to “server.php” and display the response.
📌 index.html File
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Send Data Using jQuery POST</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#contentBox {
width: 50%;
padding: 10px;
border: 1px solid black;
margin-top: 10px;
}
button {
padding: 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button id=”postBtn”>Send Data</button>
<div id=”contentBox”>Server response will be shown here…</div>
<script>
$(document).ready(function() {
$(“#postBtn”).click(function() {
$.post(“server.php”, { name: “John” }, function(response) {
$(“#contentBox”).text(response); // Displays the server response
});
});
});
</script>
</body>
</html>
📌 server.php File (Backend Code)
<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$name = $_POST[‘name’];
echo “Hello, ” . htmlspecialchars($name) . “! Your data has been received.”;
}
?>
📌 How It Works?
1️⃣ Button Click: When the “Send Data” button is clicked, jQuery sends a POST request to server.php.
2️⃣ jQuery .post() Method:
– $.post(“server.php”, { name: “John” }, function(response) {…});
– Sends name: “John” as POST data to server.php.
3️⃣ PHP Processing: server.php retrieves the name from $_POST[‘name’] and returns a response.
4️⃣ Displaying Response: The response from the server is displayed inside #contentBox.
4. Retrieve JSON Data – $.getJSON()
The $.getJSON() method fetches JSON-formatted data from a server.
👉 Example: Get a JSON object from “data.json” and display it.
📌 index.html File
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Load JSON Data Using jQuery</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#contentBox {
width: 50%;
padding: 10px;
border: 1px solid black;
margin-top: 10px;
}
button {
padding: 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button id=”jsonBtn”>Load JSON Data</button>
<div id=”contentBox”>JSON data will be displayed here…</div>
<script>
$(document).ready(function() {
$(“#jsonBtn”).click(function() {
$.getJSON(“data.json”, function(data) {
$(“#contentBox”).text(“Name: ” + data.name + “, Age: ” + data.age);
});
});
});
</script>
</body>
</html>
📌 data.json File:
{
“name”: “John Doe”,
“age”: 30
}
📌 Output
📌 How It Works?
1️⃣ Button Click: When the “Load JSON Data” button is clicked, jQuery fetches data.json.
2️⃣ jQuery .getJSON() Method:
– $.getJSON(“data.json”, function(data) {…});
– Retrieves and parses the JSON file.
3️⃣ Displaying Data:
– $(“#contentBox”).text(“Name: ” + data.name + “, Age: ” + data.age);
– Extracts name and age from data.json and displays them.
5. The General AJAX Method – $.ajax()
The $.ajax() method gives full control over AJAX requests.
👉 Example: Fetch “data.txt” with error handling.
📌 index.html File
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>AJAX Request Using jQuery</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#contentBox {
width: 50%;
padding: 10px;
border: 1px solid black;
margin-top: 10px;
}
button {
padding: 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button id=”ajaxBtn”>Load Data</button>
<div id=”contentBox”>Data will be loaded here…</div>
<script>
$(document).ready(function() {
$(“#ajaxBtn”).click(function() {
$.ajax({
url: “data.txt”, // Fetches data from this file
type: “GET”, // HTTP GET request
success: function(response) {
$(“#contentBox”).text(response); // Displays the response
},
error: function() {
$(“#contentBox”).text(“Error loading data.”); // Error handling
}
});
});
});
</script>
</body>
</html>
📌 data.txt File
Hello! This content is loaded via AJAX.
📌 Output
📌 What happens?
1️⃣ Button Click: When “Load Data” button is clicked, jQuery sends an AJAX GET request to data.txt.
2️⃣ AJAX Request:
– url: “data.txt” → Fetches the text file content.
– type: “GET” → Uses a GET request.
3️⃣ Handling Response:
– Success: Displays content inside #contentBox.
– Error: Shows “Error loading data.” if the file is missing or there’s a request failure.
Conclusion
🎯 AJAX allows dynamic content updates without page reloads.
🎯 load(), $.get(), and $.post() are used for simple data fetching.
🎯 $.getJSON() handles JSON-formatted responses easily.
🎯 $.ajax() provides full control over AJAX requests.
🎯 Error handling ensures better user experience.