AJAX—Synchronous and Asynchronous Together: Test
In this test program, we will see Ajax return one array each from two separate xmlhttp.responseTexts with the use of both Synchronous and Asynchronous Ajax scripts which run separate PHP scripts. We'll see what works and what doesn't when you run consecutive Synchronous and Asynchronous Ajax scripts. In the first four Ajax tests linked to below, we see that it's simple to return combinations of strings and arrays in a single Ajax xmlhttp.responseText, so there's rarely a need for Synchronous and Asynchronous Ajax scripts run one after another to get more data—use one script. In http://www.css-resources.com/chat-room-home-page.html we used Ajax scripts and PHP scripts so complex that we ended up using Synchronous and Asynchronous Ajax scripts run one after another. But we'll probably never need to do that again. How many chat room scripts do we need to write?
- test it AJAX-Return-Array-in-Xmlhttp-ResponseText.html
- test it AJAX-Return-String-and-Array-in-One-Xmlhttp-responseText-without-Implode.html
- test it AJAX-Return-String-and-Array-in-One-Xmlhttp-responseText-with-Implode.html
- test it AJAX-Return-Two-Arrays-in-One-Xmlhttp-responseText.html
- test it AJAX-Synchronous-and-Asynchronous-Together.html
- http://www.css-resources.com/Ajax-and-PHP-Based-Input-Filter.html
- http://www.css-resources.com/PHP-based-test-of-getting-website-info-dynamically-using-Ajax.html
- http://www.css-resources.com/PHP-based-test-of-getting-website-info-dynamically-using-separate-links-per-URL-and-Ajax.html
- http://www.css-resources.com/Ajax-and-PHP-Based-Insult-Auto-Completer.html
- http://www.css-resources.com/cms-view-website-directory-with-dynamic-descriptions-and-thumbnails.html
- http://www.css-resources.com/chat-room-home-page.html
Ajax Test and Information Links
More Ajax Related Links
What is Ajax? AJAX means Asynchronous JavaScript and XML, but it isn't a programming language. It is a new way to use existing languages. When one uses Ajax, one is exchanging data with a server and updating parts of a web page, but without reloading the whole page! For a great example of Ajax in action, see http://www.w3schools.com/Ajax/ajax_aspphp.asp or http://www.css-resources.com/Ajax-and-PHP-Based-Insult-Auto-Completer.html. Happily, one need not learn XML or even XHTML to use Ajax, although there's a whole ton one can do if one does learn those. But those are not of interest to us currently so let's stay with the problem at hand. Incidentally, Ajax can be on regular HTML or PHP pages—you need not go to XML or XHTML.
On to the code: The HTML code will be followed by the PHP code. In the HTML code, after metatags and CSS styling, we define 4 divs. The divs with the id i and id j will be visible and onscreen in this example, but in real Ajax use, they will stay offscreen with a minus 1999 pixel left property. These are the PRE-processing divs. When the Ajax routine gets back its xmlhttp.responseText from the PHP scripts they run, they store it in the i div and j div at first, as is indicated by the i.innerHTML=xmlhttp.responseText and j.innerHTML=xmlhttp.responseText lines, below. Then these results gets processed a bit and the results get stuck into the divs k and l. In this script, there is one result gotten from each of the xmlhttp.responseText responses, and the first results, an array, goes in div k and the second result, another array, goes in div l. Both results are relevant in the present script.
Note the var t = new Date().getTime(); line. Then note the fact that when the xmlhttp.open() function runs the PHP script, the URL given includes a query string with the t variable being sent along for the ride. This is because the Ajax routines, since they do not reload pages, tend to get the pages cached by the browsers. If this happens, you will get old results—the page won't change because you'll see only the cached version. Ajax programmers know that getting around this cache curse is as simple as sticking the current time in the query string. The time is always different, so the page will always be seen as new by browsers, since the whole URL is never the same twice. Problem solved. The time never gets used for anything in the PHP script it goes to. It's just an anti-cache trick. Cool, huh?
After defining arrays and variables, we use the document.getElementById() method to get a shorter way of referencing the divs by sticking the document properties into an object variable like i, j, k, or l. Then in both the first and second Ajax script areas, we make the XMLHttpRequest, and it depends on your browser which code is used—IE5 and IE6 do it differently than newer browsers.
Next IN THE SYNCHRONOUS SCRIPT section, which comes first, we run the xmlhttp.open() and xmlhttp.send() functions. Note that the open() function ends with false. If it ended with true, both scripts will fail simply because the next one is true as well and two true Ajax scripts in a row will be like asking a musician to play a flute and trombone simultaneously—it won't work. FALSE means SYNCHRONOUS, and TRUE means ASYNCHRONOUS. Two ASYNCHRONOUS scripts in a row may be a disaster, but two SYNCHRONOUS scripts in a row are fine, and a SYNCHRONOUS script followed by an ASYNCHRONOUS (like on this page) is fine as well, although an ASYNCHRONOUS script followed by a SYNCHRONOUS script is no good. What this adds up to is making sure to wait until a script is done before starting a new one. When a SYNCHRONOUS script runs it always waits until it is through getting results before it lets anything else happen anywhere, which is why either an ASYNCHRONOUS or SYNCHRONOUS script following a SYNCHRONOUS script will be fine. But ASYNCHRONOUS followed by either type is no good. Honestly, could YOU play a flute and trombone simultaneously?! The xmlhttp.responseText gets stuck right into the i div using the innerHTML property. We now process the returned data (offscreen in real use, but onscreen in our test script for clarity). Think of the i and j divs as PRE-processing divs that are offscreen, okay? The first column of the test page has two boxes representing the i div's and j div's contents. The xmlhttp.responseText that goes into the i div next gets put in the a variable and then uses the JavaScript split() function to get the array from this variable, using the | character as the delimiter. Once it is reconstituted, it gets line break tags stuck to each element, for display purposes, then the whole thing is stuck into the l div, using innerHTML.
Next IN THE ASYNCHRONOUS SCRIPT section, which comes second, we make the XMLHttpRequest just like in the synchronous script discussed above, and it depends on your browser which code is used—IE5 and IE6 do it differently than newer browsers. Then we get our xmlhttp.responseText but only when the server is in the proper readiness state. This xmlhttp.responseText gets stuck right into the j div (the lower box in the first column) using the innerHTML property. We now process the returned data (offscreen in real use, but onscreen in our test script for clarity). Think of it as offscreen, okay? The first column of the test page has its lower box representing the j div's contents. The other 2 columns are meant to be seen, and both are relevant in the present script.
Note that the xmlhttp.responseText that goes into the j div next gets put in the a variable and then uses the JavaScript split() function to get the array from this variable. The reason there's an array in the response text that is sent by the PHP script is because the PHP script put it there using mostly concatenation and the | character, which is used as the delimiter between the array elements in the PHP script. Anyway, once the array has been split using the split() function and a | delimiter, it gets line break tags stuck to each element, for display purposes. All these appended array elements get stuck into the variable w, then by use of innerHTML these get put into the k div. The xmlhttp.open() and xmlhttp.send() functions make the xmlhttp magic do its thing.
The first PHP script, test-5a.php, is quite simple. We get the u variable from the Ajax script's query string via GET. We define an array. We concatenate the u variable with each element in the array and we implode the array using | as the delimiter between array elements, and then stick all these elements in the variable $w. Then we echo this variable back to the Ajax routine that called this PHP script. The Ajax routine will receive it as xmlhttp.responseText.
The second PHP script, test-5b.php, is the same as the test-5a.php script except it defines a different array, it concatenates a different variable to its array elements, and it's called by the second, asynchronous, Ajax script, so that's where the response text goes.
This file is called: test-5.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>AJAX — Synchronous and Asynchronous Together: Test</TITLE>
<meta name="description" content="AJAX — Synchronous and Asynchronous Together: Test">
<meta name="keywords" content="AJAX,Synchronous AJAX and Asynchronous AJAX Together,AJAX: Synchronous and Asynchronous both together,javascript,php,ajax, dhtml, DHTML">
<style type="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;text-align:left;background-color:#fff;}
.i {position:absolute;top:40px;left:0px;width:200px;border:1px solid blue;padding:6px;background-color:#ddd}
.j {position:absolute;top:200px;left:0px;width:200px;border:1px solid blue;padding:6px;background-color:#ddd}
.k {position:absolute;top:40px;left:300px;width:200px;border:1px solid blue;padding:6px;background-color:#ccc}
.l {position:absolute;top:40px;left:600px;width:200px;border:1px solid blue;padding:6px;background-color:#ccc}
</style>
</head>
<body>
<center><b><h2>AJAX — Synchronous and Asynchronous Together: Test</h2></b></center>
<div class='i' id='i'></div>
<div class='j' id='j'></div>
<div class='k' id='k'></div>
<div class='l' id='l'></div>
<SCRIPT LANGUAGE="JavaScript">
var t = new Date().getTime();
var arr = new Array();var ar = new Array();
var u = "Animal: ";var q = "Verb: "; var n = 0; var v = ""; var w = "";
var k=document.getElementById("k");
var i=document.getElementById("i");
var j=document.getElementById("j");
var l=document.getElementById("l");
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("GET","test-5a.php?u="+u+"&t="+t,false);
// if true, scripts fail; FALSE = SYNCHRONOUS
xmlhttp.send();
i.innerHTML=xmlhttp.responseText;
var a=i.innerHTML;
arr=a.split("|");
for (n=0;n<arr.length;n++){v=v+arr[n]+"<BR>";}
l.innerHTML=v;
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
j.innerHTML=xmlhttp.responseText;
var a=j.innerHTML;
arry=a.split("|");
for (n=0;n<arry.length;n++){w=w+arry[n]+"<BR>";}
k.innerHTML=w;}}
xmlhttp.open("GET","test-5b.php?q="+q+"&t="+t,true);
// TRUE = ASYNCHRONOUS
xmlhttp.send();
</script>
</body>
</html>
This file is called: test-5a.php
<?php
$u=$_GET['u'];
$w='';
$a=array("Dog","Cat","Horse","Bee","Fly","Pig","Monkey","Worm","Slug");
for ($i=0;$i<count($a);$i++) {$a[$i]=$u.$a[$i];}
$w=implode("|",$a);
echo $w;
?>
This file is called: test-5b.php
<?php
$q=$_GET['q'];
$x='';
$b=array("Dig","Run","Sit","Grow","Fly","Pull","Mount","Wait","Slide");
for ($i=0;$i<count($b);$i++) {$b[$i]=$q.$b[$i];}
$x=implode("|",$b);
echo $x;
?>