error handling for AJAX div

Please support our JavaScript / DHTML / AJAX advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
Thread Solved

Join Date: Jun 2009
Posts: 5
Reputation: gromf is an unknown quantity at this point 
Solved Threads: 0
gromf gromf is offline Offline
Newbie Poster

error handling for AJAX div

 
0
  #1
Jun 27th, 2009
Hello. I've been using a very helpful AJAX-based script called AJAXTwits to load multiple Twitter timelines for a sports team into a div. The nice thing about the script is that it (1) combines multiple timelines into one chronological timeline and (2) caches the xml for faster loading. Every so often, though, Twitter's feeds go down, meaning that (i) the caching fails, (ii) the content won't load (I get stuck with the loading message), and (iii) if the problem is big enough, the whole page (not just div) breaks and throws a 404 error.

So, I'd like to add error-handling -- specifically, a pre-written message/div-content that will replace the loading message if the content doesn't load within a set amount of time. I've found some nice examples on this forum on how to handle timeouts. But those deal with a much simpler function/script syntax that does not call out to other js/php files. Being a cut/paste/emulate programmer, I'm having trouble adapting that.

The main html looks like this:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <ul id='AjaxTwits'>
  2. <li id='AjaxTwitsLoader'>
  3. <em>Loading tweets</em>
  4. </li>
  5. </ul>
  6.  
  7. <script type="text/javascript">
  8. getAjaxTwits("AjaxTwits/AjaxTwitsRequest.php", 6);
  9. </script>
Without digging into the script and php files, is there any kind of error/timeout handling that can be placed into this html? Any help appreciated!
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 954
Reputation: essential will become famous soon enough essential will become famous soon enough 
Solved Threads: 131
Featured Poster
essential's Avatar
essential essential is offline Offline
Posting Shark

Re: error handling for AJAX div

 
0
  #2
Jun 29th, 2009
You can try something like this inside the callBack function (or requestHandler).

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. var timer = 0;
  2. var requestHandler = function() {
  3. start = setTimeout( this, 1000 );
  4. var div = document.getElementById("someDivId");
  5. if ( timer === 10 && xmlHttp.readyState !== 4 ) { // If the countdown timer reaches its time limit, you can abort the current AJAX request.
  6. xmlHttp.abort();
  7. div.innerHTML = "Request failed!";
  8. return false;
  9. } if ( xmlHttp.readyState === 4 ) { // else If the timer < 10sec. and completed the final state, you can then continue to process the whole request.
  10.  
  11. clearTimeout( start );
  12. delete start;
  13. div.innerHTML = xmlHttp.responseText;
  14. } ++timer;
  15. };
Last edited by essential; Jun 29th, 2009 at 9:18 pm.
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 5
Reputation: gromf is an unknown quantity at this point 
Solved Threads: 0
gromf gromf is offline Offline
Newbie Poster

Re: error handling for AJAX div

 
0
  #3
Jun 30th, 2009
Originally Posted by essential View Post
You can try something like this inside the callBack function (or requestHandler).
Thank you for the quick response! I'm not sure I understand where to insert the code, though. I've pasted below the js file. If you could point me in the right direction, I'd appreciate it!

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. function sendAjaxRequest(url, eventhandler) {
  2. if (window.ActiveXObject) {
  3. var xhr = new ActiveXObject("Microsoft.XMLHTTP");
  4. } else if (window.XMLHttpRequest) {
  5. var xhr = new XMLHttpRequest();
  6. }
  7.  
  8. xhr.onreadystatechange = function() {
  9. if(xhr.readyState == 4)
  10. if(xhr.status == 200) {
  11. eventhandler(xhr);
  12. } else {
  13. document.body.innerHTML = xhr.responseText;
  14. }
  15. }
  16.  
  17. xhr.open("POST", url, true );
  18. xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  19. xhr.send("");
  20. }
  21.  
  22. function getAjaxTwits(url, itemCount) {
  23. var twitter = document.getElementById('AjaxTwits');
  24. var twitterload = document.getElementById('AjaxTwitsLoader');
  25.  
  26. sendAjaxRequest(url, function(ajaxRequest) {
  27. if (ajaxRequest.responseText) {
  28.  
  29. var ans = eval('(' + ajaxRequest.responseText + ')');
  30.  
  31. if (ans.item) {
  32. twitter.removeChild(twitterload);
  33.  
  34. for (var i = 0; i < itemCount; i++) {
  35. var li = document.createElement("LI");
  36. li.className = "twitter-item";
  37.  
  38. var message = hyperlinks(ans.item[i].description);
  39. message = twitter_users(message);
  40.  
  41. li.innerHTML += "<font color='#D36727'><u>" + ans.item[i].feedname + "</u>:</font> ";
  42. li.innerHTML += message + " [";
  43.  
  44. var a = document.createElement("A");
  45. // a.href = ans.item[i].url;
  46.  
  47. a.href = "http://www.twitter.com/" + ans.item[i].user;
  48.  
  49. a.className = "twitter-link";
  50. // a.innerHTML = "posted " + ans.item[i].date;
  51.  
  52. a.innerHTML = "<span style='white-space:nowrap;'>" + ans.item[i].date + "</span>";
  53.  
  54. a.target = "_blank";
  55.  
  56. li.appendChild(a);
  57.  
  58. li.innerHTML += "]";
  59.  
  60. twitter.appendChild(li);
  61. }
  62. }
  63. }
  64. });
  65. }
  66.  
  67. function hyperlinks(text) {
  68. text = text.replace(/\s(http:\/\/[a-z][a-zA-Z0-9\/\*\-\?\.\&\%\$]*)/ig," <a href=\"$1\" class=\"twitter-link\" \"target\">$1</a>");
  69. text = text.replace(/\s([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/ig," <a href=\"$1\" class=\"twitter-link\" \"target\">$1</a>$2");
  70. // match www.something.domain/path/file.extension?some=variable&another=asf%
  71. text = text.replace(/\s(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/ig," <a href=\"http://$1\" class=\"twitter-link\" \"target\">$1</a>$2");
  72.  
  73. return text;
  74. }
  75.  
  76. function twitter_users(text) {
  77. text = text.replace(/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/ig, "$1<a href=\"http://twitter.com/$2\" class=\"twitter-user\" \"target\">@$2</a>$3 ");
  78. return text;
  79. }
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 954
Reputation: essential will become famous soon enough essential will become famous soon enough 
Solved Threads: 131
Featured Poster
essential's Avatar
essential essential is offline Offline
Posting Shark

Re: error handling for AJAX div

 
0
  #4
Jun 30th, 2009
You must declare this timer variable oustide of your sendAjaxRequest( arguments... ) function.

var timer = 0; // Declared as global variable.
The rest of the editing procedure will take part on this portion of the script:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. xhr.onreadystatechange = function() {
  2. start = setTimeout( this, 1000 );
  3. if ( timer === 10 && xhr.readyState !== 4 ) { // Specify the number of timer limit, it is currently set to 10sec delay.
  4.  
  5. /* Add the things that you need to process if the requested content failed to load with the given time limit. */
  6.  
  7. clearTimeout( start );
  8. xhr.abort();
  9. document.body.innerHTML = "Loading failed!";
  10. return false;
  11. }
  12. if ( xhr.readyState === 4 && xhr.status === 200 ) { //The request completed the execution over its timer limit.
  13. clearTimeout( start );
  14. delete start;
  15. document.body.innerHTML = xhr.responseText;
  16. } ++timer;
  17. }; // Callback reference ENDED.

hope it goes wel with your AJAX handler...

essential
Last edited by essential; Jun 30th, 2009 at 4:42 am.
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 5
Reputation: gromf is an unknown quantity at this point 
Solved Threads: 0
gromf gromf is offline Offline
Newbie Poster

Re: error handling for AJAX div

 
0
  #5
Jun 30th, 2009
Thank you for your quick response again. I apologize that I'm still not getting it. I'm really sorry. No doubt I'm in over my head at this point, but I'd like to get it figured out and to learn from it.

Based on what you suggested, I did two things (I'm sure neither of which was correct). First, I added the global timer variable into the php file (insertion in bold):
<?php

  var timer = 0; // Declared as global variable.

	//include AjaxTwits and create an object
	include('AjaxTwits.php');
	$ajaxTwits = new AjaxTwits;
	
	//set the cache to a writable folder, to save xml files
	$ajaxTwits->cachefolder = "ajaxtwits/cache";
	//the amount of minutes the feed is cached
	$ajaxTwits->cacheTime = 2;
	
	//the amount of items you'll show
	$ajaxTwits->itemCount = 15;
	
	//add your twitter account feeds
	$ajaxTwits->addTimeline("xxxx", "xxxx");
	$ajaxTwits->addTimeline("yyyy", "yyyy");
		
	
	//disable human time and output just Y/m/d date format
	$ajaxTwits->humanTime = true;
	
	//this will output the information, JSON is for the Javascript application
	$ajaxTwits->outputFeed("json");
?>

Second, I added the script you suggested into my preexisting js as shown below (insertion in bold):
function sendAjaxRequest(url, eventhandler) {
	if (window.ActiveXObject) {
		var xhr = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		var xhr = new XMLHttpRequest();
	}

	xhr.onreadystatechange = function() {
   start = setTimeout( this, 1000 );
   if ( timer === 5 && xhr.readyState !== 4 ) { // Specify the number of timer limit, it is currently set to 10sec delay.

/* Add the things that you need to process if the requested content failed to load with the given time limit. */

  
	
	
	xhr.onreadystatechange = function() {
	if(xhr.readyState == 4)
		if(xhr.status == 200) {
			eventhandler(xhr);
		} else {
			document.body.innerHTML = xhr.responseText;
		}
	}

	xhr.open("POST", url, true );
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("");
}


function getAjaxTwits(url, itemCount) {
	var twitter = document.getElementById('AjaxTwits');
	var twitterload = document.getElementById('AjaxTwitsLoader');
	
	sendAjaxRequest(url, function(ajaxRequest) {
		if (ajaxRequest.responseText) {
					
			var ans = eval('(' + ajaxRequest.responseText + ')');

			if (ans.item) {
				twitter.removeChild(twitterload);
				
				for (var i = 0; i < itemCount; i++) {
					var li = document.createElement("LI");
					li.className = "twitter-item";				
									
					var message = hyperlinks(ans.item[i].description);
					message = twitter_users(message);
					
					li.innerHTML += "<font color='#D36727'><u>" + ans.item[i].feedname + "</u>:</font> ";
					li.innerHTML += message + " [";
									
		var a = document.createElement("A");
					//	a.href = ans.item[i].url;
					
						a.href = "http://www.twitter.com/" + ans.item[i].user;
											
						a.className = "twitter-link";
					//	a.innerHTML = "posted " + ans.item[i].date;
					
					a.innerHTML = "<span style='white-space:nowrap;'>" + ans.item[i].date + "</span>";
					
					a.target = "_blank";
											
					li.appendChild(a);
					
					li.innerHTML += "]";
					
					twitter.appendChild(li);
				}
			}
		}
	});	


function hyperlinks(text) {
	text = text.replace(/\s(http:\/\/[a-z][a-zA-Z0-9\/\*\-\?\.\&\%\$]*)/ig," <a href=\"$1\" class=\"twitter-link\" \"target\">$1</a>");
	text = text.replace(/\s([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/ig," <a href=\"$1\" class=\"twitter-link\" \"target\">$1</a>$2");
	// match www.something.domain/path/file.extension?some=variable&another=asf%
	text = text.replace(/\s(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/ig," <a href=\"http://$1\" class=\"twitter-link\" \"target\">$1</a>$2");      
    
	return text;
}

function twitter_users(text) {
    text = text.replace(/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/ig, "$1<a href=\"http://twitter.com/$2\" class=\"twitter-user\" \"target\">@$2</a>$3 ");
    return text;
}

 clearTimeout( start );
   xhr.abort();
   document.body.innerHTML = "Loading failed!"; 
   return false;
   }
 if ( xhr.readyState === 4 && xhr.status === 200 ) { //The request completed the execution over its timer limit.
   clearTimeout( start );
   delete start;
   document.body.innerHTML = xhr.responseText;
   } ++timer;
}; // Callback reference ENDED.

}

If you point out where I'm erring, I would really appreciate it! Thanks again!
Last edited by gromf; Jun 30th, 2009 at 3:16 pm. Reason: mistaken paste job
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 5
Reputation: gromf is an unknown quantity at this point 
Solved Threads: 0
gromf gromf is offline Offline
Newbie Poster

Re: error handling for AJAX div

 
0
  #6
Jun 30th, 2009
I just figured out that I completely misunderstood the direction that Essential so generously gave. I'm having trouble editing my response above, though, so I'm just replying.

I'm still not sure I added the global timer variable properly. But I think this is what you had in mind for the insertion (the bolded part replacing the old hxr.onreadystatechange handling:

function sendAjaxRequest(url, eventhandler) {

	if (window.ActiveXObject) {
		var xhr = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		var xhr = new XMLHttpRequest();
	}

xhr.onreadystatechange = function() {
   start = setTimeout( this, 1000 );
   if ( timer === 5 && xhr.readyState !== 4 ) { // Specify the number of timer limit, it is currently set to 10sec delay.

/* Add the things that you need to process if the requested content failed to load with the given time limit. */

   clearTimeout( start );
   xhr.abort();
   document.body.innerHTML = "Loading failed!"; 
   return false;
   }
 if ( xhr.readyState === 4 && xhr.status === 200 ) { //The request completed the execution over its timer limit.
   clearTimeout( start );
   delete start;
   document.body.innerHTML = xhr.responseText;
   } ++timer;
}; // Callback reference ENDED.

	xhr.open("POST", url, true );
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("");
}

function getAjaxTwits(url, itemCount) {
	var twitter = document.getElementById('AjaxTwits');
	var twitterload = document.getElementById('AjaxTwitsLoader');
	
	.....
Unfortunately, it's still not working....
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 954
Reputation: essential will become famous soon enough essential will become famous soon enough 
Solved Threads: 131
Featured Poster
essential's Avatar
essential essential is offline Offline
Posting Shark

Re: error handling for AJAX div

 
0
  #7
Jul 1st, 2009
Here's a complete document sample that you can run offline with your browser. Just be sure that you'll provide valid test file on its sendAjaxRequest(someValidFile.txt) url parameter.

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <?xml version="1.0" encoding="utf-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  4. <html id="xhtml10S" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  5. <head profile="http://www.w3.org/2005/10/profile">
  6. <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
  7. <meta http-equiv="Window-Target" content="_top" />
  8. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  9. <meta http-equiv="Content-Style-Type" content="text/css" />
  10. <meta http-equiv="Content-Script-Type" content="text/javascript" />
  11. <title>Free Live Help!</title>
  12. <script type="text/javascript">
  13. // <![CDATA[
  14. var timer = 0;
  15. var xhr;
  16. var method = "POST";
  17.  
  18. var clock = function() {
  19. countdown = setTimeout( "clock()", 1000 ); ++timer;
  20. return timer;
  21. };
  22.  
  23. var sendAjaxRequest = function( url, eventhandler ) {
  24. var div = (( "getElementById" in document ) ? document.getElementById("testdiv") : document.all.testdiv );
  25.  
  26. try {
  27. if ( "XMLHttpRequest" in window ) {
  28. xhr = new XMLHttpRequest();
  29. } else if ( "ActiveXObject" in window ) {
  30. var client = [ "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
  31. try {
  32. for ( var i = 0; i < client.length; i++ ) {
  33. xhr = new ActiveXObject( client[ i ] );
  34. }
  35. } catch( er ) { }
  36. }
  37. } catch( e ) {
  38. if ( "createRequest" in window ) {
  39. xhr = window.createRequest();
  40. } xhr = null;
  41. } if ( xhr !== null ) {
  42. (( "overrideMimeType" in xhr ) ? xhr.overrideMimeType("text/xml") : xhr );
  43. xhr.onreadystatechange = function() {
  44. clock(); // Activate the timer
  45. timer = (( timer < 10 ) ? "0" : "" ) + timer;
  46. if ( timer < 5 && xhr.readyState === 4 ) {
  47. clearTimeout( countdown );
  48. delete countdown;
  49. div.innerHTML = "<p style=\"color : purple;\">Request completed in <span style=\"color : red;\">" + timer + "</span> seconds!</p>\n";
  50. div.innerHTML += "<hr />\n";
  51. div.innerHTML += "<span style=\"letter-spacing : 4px; color : green;\">" + xhr.responseText + " —</span>";
  52. return true;
  53. } xhr.abort();
  54. clearTimeout( countdown );
  55. delete countdown;
  56. div.innerHTML = "<span style=\"letter-spacing : 4px; color : purple;\">Request failed —</span>";
  57. };
  58. xhr.open( method, encodeURIComponent( url ), true );
  59. (( method === "POST" && "setRequestHeader" in xhr ) ? xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : xhr );
  60. xhr.send( "" );
  61. return true;
  62. } alert( "Your browser does not handle AJAX Request!" );
  63. };
  64. window.onload = function() {
  65. sendAjaxRequest("test.txt");
  66. };
  67. // ]]>
  68. </script>
  69. </head>
  70. <body>
  71. <div id="testdiv"></div>
  72. </body>
  73. </html>
Last edited by essential; Jul 1st, 2009 at 12:40 am.
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 5
Reputation: gromf is an unknown quantity at this point 
Solved Threads: 0
gromf gromf is offline Offline
Newbie Poster

Re: error handling for AJAX div

 
0
  #8
Jul 9th, 2009
Well, with BIG BIG thanks to 'essential' for his support, I can finally mark this solved. Here is the key part of the timeout handling excerpt:

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. var timer = 0;
  2. var xhr;
  3. var method = "POST";
  4. var clock = function() {
  5. countdown = setTimeout( "clock()", 1000 ); ++timer;
  6. return timer;
  7. }
  8.  
  9. var sendAjaxRequest = function( url, eventhandler ) {
  10. var div = (( "getElementById" in document ) ? document.getElementById("AjaxTwitsLoader") : document.all.AjaxTwitsLoader );
  11. try {
  12. if ( "XMLHttpRequest" in window ) {
  13. xhr = new XMLHttpRequest();
  14. } else if ( "ActiveXObject" in window ) {
  15. var client = [ "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
  16. try {
  17. for ( var i = 0; i < client.length; i++ ) {
  18. xhr = new ActiveXObject( client[ i ] );
  19. }
  20. } catch( er ) { }
  21. }
  22. } catch( e ) {
  23. if ( "createRequest" in window ) {
  24. xhr = window.createRequest();
  25. } xhr = null;
  26. } if ( xhr !== null ) {
  27. (( "overrideMimeType" in xhr ) ? xhr.overrideMimeType("text/xml") : xhr );
  28. xhr.onreadystatechange = function() {
  29. clock(); // Activate the timer
  30. if ( timer < 10 ) {
  31. if ( xhr.readyState === 4 ) {
  32. // if ( xhr.status === 200 ) {
  33. clearTimeout( countdown );
  34. delete countdown;
  35. eventhandler( xhr );
  36. // }
  37. } return true;
  38. } else {
  39. div.innerHTML = "<img src='/images/twitter-bird-error2.gif' align='left' style='margin-left:-10px;'><br><center><i>temporarily unable to connect to Twitter....</i>";
  40. }
  41. }; xhr.open( "POST", url, true );
  42. //(( method === "POST" && "setRequestHeader" in xhr ) ? xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : xhr );
  43. xhr.send( "" );
  44. return false;
  45. } //alert( "Your browser does not handle AJAX Request!" );
  46.  
  47.  
  48. }
  49.  
  50. function getAjaxTwits(url, itemCount) {
  51.  
  52. ...
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC