So Here is our question what is Ajax and how does it work?
Ajax stands for Asynchronous JavaScript and XML
Ajax is used to exchange data with a web server
asynchronously. (asynchronously means it sends and receives data in the background and does not reload the page every time in doing so).The reason Ajax is famous is that it only changes the parts of the page that we are updating or changing instead of reloading the whole web page.
Ajax supports non-blocking calls means codes can run simultaneously.
When we are using Ajax, JavaScript will make a request to the server and after getting a response from the server, it will interpret the response and update or show the result on the user screen.
ajax asynchronously communicates with the server using XMLHttpRequest. example:
let ajaxXhr = new XMLHttpRequest();
here XMLHttpRequest() is an object request we have created and stored in the variable name ajaxXhr.
How Ajax Works :
When an event(means a user clicking a button, hovering a mouse, etc.) occurs on a webpage.
then this awakes the Ajax engine.
ajax engine sends the XMLHttpRequest to the server.
then the server gives the response to the Ajax engine in the format of JSON or XML.
after getting the response it will update the webpage(not the whole).
easy example of ajax running:
btn.addEventListener("click", ajaxRun);
function ajaxRun(){
let xhr = new XMLHttpRequest();
xhr.open("GET", "file.txt", true);
xhr.send();
}
from the above example, we add an event listener to the button (btn), which means when we click btn , it will run the ajaxRun function.
in the ajaxRun function, it will create a new XMLHttpRequest() object,
and store it in xhr variable.
then we use the object method on xhr for further action.
we use the open method in which we have three parameters
open(method, URL, async) i.e. it tells where we are transmitting the data. (talk about detail in the next part).send method tells us that the request is sent.
Use of Ajax :
it is used for creating dynamic Web apps.
With Ajax, we can send and receive data without reloading the webpage.
It makes our web apps interactive and faster.
next in part b