The Ajax object is a very powerful tool that allows us to communicate with the web server, in the background. The Ajax object is repleat with multiple events so we can continually be updated as the what is going on with the Ajax object while it is working.
While quite often, code for creating the Ajax object is a simple one line var ajaxRequest = new XMLHttpRequest();
, while in most cases this will work, in some Javascript environments, this method of creating the Ajax object will fail and so will any of your resulting code.
A more complete and safe way to create the Ajax object and ensure that it is created is to create a variable that calls a function that creates the Ajax object taking into account other possible various Javascript environments is to create a variable that calls the function that creates the Ajax object and then the funtion returns the successfully created Ajax object ...
This is the function that actually creates the Ajax object, taking into account most all possible Javascript environments.
Once the Ajax object has been successfully created, you can then use it to communicate with a script usually php that processes the data you send it. The data you send the php script is usually in the form of the query string part of the url where the php script resides.
Since you have used the Ajax object to send data to the php script on the web server, at this point you want to monitor various events of the Ajax object. These events either keep you updated as to the progress of the communication between the Ajax object and your web server or notify you when the data returned by the php script is ready for you to process and do stuff with.
The onreadystatechange
event of the Ajax object keeps you updated as to the current state or progress of communications between the web server and the Ajax object.
The error
event of the Ajax object notifies you if there is an error with the Ajax object so if code does not run as expected, because of an error, you will be given notification of the trouble via this event of the Ajax object.
The onload
event of the Ajax object occurs when the Ajax object has return the result of the code that was processed on the server. In this event you take the data returned by the Ajax object and process it to do what you want it to do.
The entire code required to use the Ajax object succesfully is all put together in the textbox below.