Let's start with a requirement. You are required to update part of your web page and (only part of your web page) asynchronously. When? Well when a button called 'Update with AJAX' is clicked!
And what are you required to update it to? The contents of a file that reside on your server.
Ok let's look at the solution.
Simple Ajax / Javascript Example
Very simple Javascript / Ajax Example
This page shows some very simple JavaScript / Ajax in action!
This will text be updated!
Now let's look at the salient points here:
- The HTML is pretty simple. There is a paragraph with the "id".
This is the paragraph that will be updated when the Ajax Update
button is pressed. - The Javascript function loadDoc() is defined in the HTML header.
- The loadDoc() function creates a XMLHttpRequest object (or an ActiveXObject for
those annoying browsers!) - The XMLHttpRequest is pretty cool. This is what facilitates the AJAX request.
It has a event property onreadystatechange. When this property an anonymous
function will execute. - The anonymous function, checks a property readyState. When this property is 4 it means that the server has finished the request and the response is ready.
- When the response is ready, the function checks another property responseText
which contains the response from the server. It updates the paragraph with the response.
So what actually sends the request?- The open API sets up the request. It states what type a request (Get, parameter 1), the URL / URI (ajax_info.txt, parameter 2) and that the request should be
asynchronous (false, parameter 3). - The send API sends the request. In this case, no parameter is included.
This means the the client sends no request to the Server. It can if it wants to. It would simply include a parameter in the send() API which is the data the client will
send to the server.
Now to get this working all you need is this file and a file named ajax_info.txt on the same Server! Enjoy! - The open API sets up the request. It states what type a request (Get, parameter 1), the URL / URI (ajax_info.txt, parameter 2) and that the request should be
No comments:
Post a Comment