coming soon …
Category : ajax
Problem
Learn and demonstrate some simple AJAX.
To produce a clear, clean example – as small as possible.
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.
Example
- Click 'see demo'.
- Click image to see updated date.
- 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:
Reference
[tags]AJAX tutorial, AJAX, AJAX demonstration, PHP, Learn AJAX[/tags]
For excellent doco (as always) check out Wiki.
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.
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.
Example
Header set cache-control "no-cache"
Header set Pragma "no-cache"
Header set Expires "-1"
Reference
[tags][/tags]
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.
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.
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 ...
--------------------------------------------------
Reference
[tags][/tags]