Simple XMLHttpRequest (AJAX)

Here I am illustrating how to do a simple XMLHttpRequest to do an asynchronous call to a file. I first created an index.html page where I created a constructor of "xhr = new XMLHttpRequest(); ".  And then on another simple text file. I put the text of "AJAX - XMLHttpRequest!". Then I defined an if else statement for what to do in case of an error (404) or success (200) message. Below I am saying that if there is a 200 success message and my document is found to then create a window pop up alert with the contents of the file. This could be used to perhaps pop-up a verification code or something else that I want to load asynchronously in regards to the rest of the data being loaded. 

This creates an alert box that displays the contents of the dom.txt file.
Next I create an error message to be displayed in the console if the file is not found. And finally I finish defining the xhr options in that here I am getting an object called dom.txt and that I want it to load asynchronously. 


And now when I load the page and the Javascript runs it does the AJAX(Asynchronous Javascript and XML) call and returns the contents of my dom.txt file to the alert box that is popped up on screen. And that's it. That is in its most simplest form an AJAX call.

AJAX call for a text file's contents to put in an alert box.





Comments