Ajax api
AJAX API Request in HTML, CSS, and JavaScript
AJAX (Asynchronous JavaScript and XML) allows fetching data from an API without reloading the webpage.
---
1. Folder Structure
ajax-api/
│── index.html
│── assets/
│ ├── css/
│ │ ├── styles.css
│ ├── js/
│ │ ├── script.js
---
2. HTML Code (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX API Example</title>
<link rel="stylesheet" href="assets/css/styles.css">
</head>
<body>
<h1>Random User Data</h1>
<button id="fetchData">Get User</button>
<div id="userData"></div>
<script src="assets/js/script.js"></script>
</body>
</html>
---
3. CSS Code (styles.css)
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
button {
background: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
button:hover {
background: darkblue;
}
#userData {
margin-top: 20px;
font-size: 18px;
}
---
4. JavaScript Code (script.js)
document.getElementById("fetchData").addEventListener("click", function() {
// Create an AJAX request
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://randomuser.me/api/", true);
xhr.onload = function() {
if (xhr.status === 200) {
let response = JSON.parse(xhr.responseText);
let user = response.results[0];
document.getElementById("userData").innerHTML = `
<p><strong>Name:</strong> ${user.name.first} ${user.name.last}</p>
<p><strong>Email:</strong> ${user.email}</p>
<img src="${user.picture.medium}" alt="User Image">
`;
} else {
document.getElementById("userData").innerHTML = "Error fetching data!";
}
};
xhr.send();
});
---
5. How It Works
1. When the "Get User" button is clicked, an AJAX request is made to the Random User API.
2. The response contains user details, which are displayed dynamically.
3. The page does not reload, making it a smooth experience.
---
Do you need a different API integration or extra features?
Comments
Post a Comment