Smallest AJAX example in the world?

[problem]

Learn and demonstrate some simple AJAX.

To produce a clear, clean example – as small as possible.

[/problem]

[solution]

Can a smaller working AJAX example be produced?

Always a believer in keeping it simple & find it easier to learn something complex, by making it as small as possible. See Example.

[/solution]

[example]

  1. Click ‘see demo’.
  2. Click image to see updated date.
  3. Click ‘view the code’.

Here is the code:

<?php

if(isset($_GET['subreq'])) {
echo date('l dS of F Y h:i:s A');
exit(0);
}
?>
<img src=/icons/a.png onClick="javascript:
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } catch (E) { xmlhttp = false; }
}
@end @*/
if(!xmlhttp) { xmlhttp=new XMLHttpRequest(); }
xmlhttp.open('GET','index.php?subreq=y', true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) { document.getElementById('output_div').innerHTML = xmlhttp.responseText; }
}
xmlhttp.send(null);
">
<div id='output_div'>click image above to put date here</div>

Or Click this link:

[/example]

[reference]

[tags]AJAX tutorial, AJAX, AJAX demonstration, PHP, Learn AJAX[/tags]

For excellent doco (as always) check out Wiki.

[/reference]

AJAX Gotcha Browser caching

[problem]

Spent many hours debug my code on elizaclaire.darlingranges.com.

I kept wondering why, whenever I updated the code – it did not get reflect through.

[/problem]

[solution]

Eventually but printing the date within the sub request, I found the browser was caching the sub request!

The fix was very easy, to force a header under apache – turning off caching.

[/solution]

[example]

Header set cache-control "no-cache"
Header set Pragma "no-cache"
Header set Expires "-1"

[/example]

[reference]

[tags][/tags]

[/reference]

AJAX And Javascript Functions Gotcha

[problem]

Spent many further hours debug my code on elizaclaire.darlingranges.com.

None of my javascript functions worked, in the resulting sub-request. Tried all sorts, even setting up an AJAX call, within the sub-request. Nothing worked.

[/problem]

[solution]

Eventually through masses of trial and error, “discovered” I had to define the javascript function, with the main body of the code.

In other words, within the subrequest made through AJAX you can have javascript triggers (onclick, onsubmit, onchange …) – but have them call functions previous define in your original web page.

[/solution]

[example]


------------------- demo.htm ------------------

....
function reset_cty() { .... }
...
var url="page_with_call_reset_cty.htm"
xmlhttp.open("GET",url, true)
-------------------------------------------------

----------- page_with_call_reset_cty.htm --------
...
... onclick = ... reset_cty ...

--------------------------------------------------

[/example]

[reference]

[tags][/tags]

[/reference]