Ajax Response in JavaScript
? AJAX Response in JavaScript
An AJAX response is the data that a server sends back to your JavaScript code after making an AJAX request. You can use this data to update the webpage dynamically without reloading it.
? Common Response Types
| Type | Description | Usage Example |
|---|---|---|
| Text | Plain text | "Hello from server" |
| HTML | HTML code snippet | "<p>Loaded content</p>" |
| JSON | Structured data (key-value) | {"name": "John", "age": 25} |
| XML | Older format for structured data | <user><name>John</name></user> |
? Example 1: Text Response (Using fetch())
HTML:
<button onclick="loadText()">Load Text</button><div id="result"></div>JavaScript:
function loadText() { fetch("message.txt") .then(response => response.text()) .then(data => { document.getElementById("result").innerHTML = data; });}Server File (message.txt):
Hello from the server!? Example 2: JSON Response (Using fetch())
HTML:
<button onclick="getUser()">Get User Info</button><div id="userInfo"></div>JavaScript:
function getUser() { fetch("user.php?id=1") .then(response => response.json()) .then(data => { document.getElementById("userInfo").innerHTML = "Name: " + data.name + "<br>Email: " + data.email; });}PHP (user.php):
<?php$user = ['name' => 'Alice', 'email' => 'alice@example.com'];echo json_encode($user);?>? Example 3: Handling Error Responses
fetch("missing-file.php") .then(response => { if (!response.ok) { throw new Error("HTTP Error: " + response.status); } return response.text(); }) .then(data => { console.log("Success:", data); }) .catch(error => { console.error("Error:", error.message); });? Using AJAX Response with XMLHttpRequest
const xhr = new XMLHttpRequest();xhr.open("GET", "data.json", true);xhr.onload = function () { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); console.log("Name:", data.name); }};xhr.send();? Summary
AJAX responses can be text, HTML, JSON, or XML.
Use
.text()or.json()methods withfetch()to process them.You can dynamically update your webpage based on the response data.
Always check for errors to handle failed responses gracefully.
Would you like to see an example of using an AJAX response to populate a table or dropdown dynamically?