Quick and Dirty AJAX Tutorial - A More Advanced Approach
(Page 3 of 4 )
To give a more real-world example of how AJAX can be used, consider the following revised AJAX:
<script type="text/javascript"> function createRequestObject() { var ro; var browser = navigator.appName; if(browser == 'Microsoft Internet Explorer') { ro = new ActiveXObject("Microsoft.XMLHTTP"); } else { ro = new XMLHttpRequest(); } return ro; }
function handleTimestamp() { if(map.handleTimestamp.ajax.readyState == 4) { var response = map.handleTimestamp.ajax.responseText; if(response != timestamp) { timestamp = response; } } }
function handleFoo() { if(map.handleUsersOnline.ajax.readyState == 4) { var response = map.handleFoo.ajax.responseText; if(response != 'noupdate') { document.getElementById('foo').innerHTML = response; } } }
var map = { handleTimestamp:{ ajax: createRequestObject(), handler: handleTimestamp }, handleFoo:{ ajax: createRequestObject(), handler: handleFoo } };
function sndReq(timestamp, action) { map[action].ajax.open('get', 'ajax.php?time='+timestamp+ '&action='+action+'&nocache='+Date()); map[action].ajax.onreadystatechange = map[action].handler map[action].ajax.send(null); }
function reqUpdates(timestamp) { sndReq(timestamp, 'handleTimestamp'); sndReq(timestamp, 'handleFoo'); }
var timestamp = '<?php echo time(); ?>'; setInterval("reqUpdates(timestamp)", 30000); </script> |
Woo! That's a lot of revisions, eh? The createRequestObject() is the same, except we're no longer assigning it to an http variable because we want each div being updated to have its own request object (to prevent conflicting data). For the same reason, we're using JavaScripts map to help divide everything up. So now instead of having one handleResponse() function, we can create a separate handler function for each thing we want to update.
In the above example we have two handler functions, handleTimestamp(), and handleFoo(). Also note the addition of the line:
var timestamp = '<?php echo time(); ?>'; |
Here we set a JavaScript variable with the value of the current server time. We can use this timestamp to check if there are any new updates in our database. If there are new updates, then not only will we instruct handleFoo() to display them for our visitors, but handleTimestamp() will update our JavaScript timestamp variable so we can start over and only send fresh content! MMmm it's like I just ate a breath-mint, so fresh...
You will also notice some revisions to our sndReq() function, which now sends a query string to our ajax.php page to work with. The timestamp variable, as mentioned, will help determine what content is new. The action variable will determine what we're updating (what div, for example). The nocache variable in the query string is being set with the current JavaScript (or client-side) time in order to prevent certain browsers from calling a cached version of the page, as obviously that would be bad.
Now onto the revised ajax.php:
<?php if(isset($_REQUEST['time'], $_REQUEST['action'])) { // never trust client-side data $timestamp = ctype_digit($_REQUEST['time']) ? $_REQUEST['time'] : time();
switch($_REQUEST['action']) { case 'handleTimestamp': echo time(); break; case 'handleFoo': $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $query = "SELECT * FROM mysql_table WHERE UNIX_TIMESTAMP( date_field) > '$timestamp'"; $result = mysql_query($query); if(mysql_num_rows($result) > 0) { // output your updates } else { echo 'noupdate'; } mysql_close($link); break; } exit(); } ?> |
This should be pretty straight forward. First, since we're going to be using our timestamp in a database query, we want to make sure it's actually a numerical value to prevent some type of injection attack. Next we enter into a switch loop to determine what code to execute, depending on what action is being called. The case handleFoo is what should really interest you, as you can see how easy it is to check for new updates knowing we will always have a current timestamp. If no updates are available, we just send the text "noupdate" which our JavaScript will use to process accordingly.
If you want to update an additional div, simply add a new handler function to the JavaScript and follow the same syntax as the other two existing ones. The same goes for updating ajax.php.
Next: Things to Consider >>
More Miscellaneous Articles
More By notepad