Interacting With a Program On the Server
The way Ajax scripts work is often disconcerting because of the asynchronous
aspect which makes that the actions are not executed in sequence to follow
the order of the instructions, but they are executed according to the availability
of the server instead.
Whereas request are launched, but even if the result is not obtained yet,
the following instructions are executed.
To avoid this problem, one have to use callbacks, functions given in parameters
of other functions. It is very simple to do that as we will show it.
In a basic example, we will execute a GET command, which will immediately follow a POST command, and which will depend on the result of this one.
The POST command sends data to a PHP script which perform some operations
and put the result of its calculations in a text file.
The GET command retrieve this file and displays the results. The display function
will be called from a location where it will follow the end of the execution
of the POST command and not before.
The POST command
The POST request is included in the Write function:
function write(url, data, fun) { var xhr = AACreate(); xhr.onreadystatechange=function() { if(xhr.readyState == 4) { if(fun != null) fun(); } }; xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(data); }
The function uses a callback in parameter, fun, which is optional. It calls
the script given in "url" with the parameters given in "data".
In this case, the Write function is called with in parameter the name of the
"retrieve" function :
write("demo-chain.php", "file=demo-post.txt&content=" + content, retrieve);
The GET command
This GET request is made by the "retrieve" function given in parameter of the preceding function, thus it is executed only after the POST request was performed:
function retrieve(storage) { var xhr = create(); xhr.onreadystatechange=function() { if(xhr.readyState == 4) { var content = xhr.responseText; display(content, storage); } } xhr.open("GET", url , true); xhr.send(null); }
This function uses another function in callback, "display", which display the contents returned by the XHR object into the element given in parameter.
function display(content, storage) { storage.innerHTML = content; }
Download the demonstration
- ajax-chain.zip
Warning! Although this principle works well in the demonstration, when used in production, I realized it does not work for all users. Then to be used incidentally.