DEV Community

Cover image for Learn Ajax in simple way for Beginners (part - a)
Coder Pink
Coder Pink

Posted on

Learn Ajax in simple way for Beginners (part - a)

So Here is our question arise what is ajax and how it is work?

  • Ajax stands for Asynchronous JavaScript and XML

  • Ajax is used to exchange data with a web server
    asynchronously.(asynchronously means it send and receive data in background and do not reload the page every time in doing so).

  • The reason ajax is famous, for it only change the parts of the page which we are updating or changing instead of reloading the whole web page.

  • Ajax support non-blocking calls means codes can run simultaneously.

When we are using ajax , JavaScript will make a request to the server and after getting response from server, it will interpret the response and update or show the result on the user screen.

ajax asynchronously communicate with server using XMLHttpRequest.
example:

let ajaxXhr  = new XMLHttpRequest();
Enter fullscreen mode Exit fullscreen mode

here XMLHttpRequest() is object request we have created and stored it in variable name ajaxXhr.

How ajax Works :

  • When an event(means like a user click a button, hover a mouse etc.) occurred on a webpage.

  • then this awakes the ajax engine.

  • ajax engine send the XMLHttpRequest to the server.

  • then server give the response to the ajax engine in the format of JSON or XML.

  • after getting the response it will update the webpage(not whole).

easy example of ajax running:

btn.addEventListener("click", ajaxRun);

function ajaxRun(){
let xhr = new XMLHttpRequest();
xhr.open("GET", "file.txt", true);
xhr.send();
}
Enter fullscreen mode Exit fullscreen mode

from above example, we add a event listener to button (btn), means when we click btn , it will run ajaxRun function.
in ajaxRun function, it will create a new XMLHttpRequest() object,
and store it in xhr variable.
then we use object method on xhr for further action.

  • we use open method in which we have three parameter
    open(method, URL , async) i.e it tells where we are transmitting the data. (talk about detail in next part).

  • send method tells us that the request is send.

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

Hope it help... we talk about it more in ajax part-b

Top comments (3)

Collapse
 
ahm_freeman profile image
Francis Enechukwu🇳🇬🇨🇦

Thanks for this concise tutorial on Ajax it actually help me understand Ajax better.

Collapse
 
coderpink profile image
Coder Pink

My pleasure.

Collapse
 
200_sucess_404-error profile image
kevin cross sr

perfectly explained, looking forward to part 2