What AJAX(Asynchronous JavaScript and XML)?
It is a set of web development techniques, that help the web page to update data asynchronously by establishing communication with the server without loading the webpage(Dats exchange asynchronous behind the sean).
Why AJAX?
In general, if you want to send data to the server, the page has to reload, which is a bad user experience. But in the case of AJAX, it allows certain parts of the page to update asynchronously without reloading the page.
Stapes of AJAX
- Event occurs on page.
- Send a request to the server.
- Receive the response data.
- Update data and UI of the page.
In AJAX communication is happening asynchronously with the help of HTTP protocol and the medium is not only XML objects but JSON objects too.
How AJAX?
To implement AJAX I am creating a "Random joke" website. To send a request to the server I am using the XHR (XMLHttpRequest) object, which is provided by the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Random Jokes</title>
<style>
body {
height: 100vh;
background-color: rgb(69, 68, 68);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow: hidden;
}
.btn button {
background-color: #828181;
color: white;
text-align: center;
border-radius: 10px;
border: none;
padding: 10px;
margin: 10px;
font-size: 14px;
}
.display {
display: flex;
align-items: center;
justify-content: center;
height: 300px;
width: 500px;
border-radius: 10px;
background-color: white;
padding: 10px;
}
#joke {
text-wrap: wrap;
font-size: large;
text-align: center;
}
</style>
</head>
<body>
<div class="btn">
<button onclick="getAJoke()">Tell me a joke</button>
</div>
<div class="display">
<div id="joke">Click button to laugh!!</div>
</div>
<script>
const jokeDiv = document.getElementById("joke");
const getAJoke = () => {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://v2.jokeapi.dev/joke/Any?type=single");
xhr.send();
xhr.onload = () => {
if (xhr.status == 200) {
const data = JSON.parse(xhr.responseText);
jokeDiv.innerText = data.joke;
}
};
xhr.onerror = () => {
console.log("Error");
};
};
</script>
</body>
</html>
- I attached
onclick
event to the button, which is callinggetAJoke ()
after getting clicked. - Creating a new XHR object and using
xhr.open()
which is taking arguments 'GET'(HTTP method) and URL. Then send a request byxhr.send()
- After the request-response cycle the
onload
method is called. - As server response in JSON(JavaScript Object Notation) which is a string. To update the data I am using
Object.parse()
to convert into objects.
Top comments (0)