You are browsing the archive for XHR.

Parsing ATOM/RSS feeds from JavaScript code using Dojo

August 22, 2012 in Dojo, JavaScript

One of the most common requirements is to parse RSS and ATOM feeds from the JavaScript code. In this post, I show you how to parse both RSS and ATOM feeds from your JavaScript code using Dojo.

Parsing ATOM feed

The next code listing is an example which loads and parses the ATOM feed from the "atom.xml" file that contains an ATOM XML.

<script type="text/javascript">
dojo.addOnLoad(function() {
	  var resultPanelID = "resultPanel";
	  
	  // Parse ATOM feed
	  dojo.xhrGet({
	     url: "atom.xml",
	     preventCache: true,
	     handleAs: "xml",
 	     load: function(xmlDoc, ioArgs){		 
	         var i = 0;
	         var output = "";
	      
	         var node = xmlDoc.getElementsByTagName("feed").item(0);
	     
	         if (node == null) {
		         console.debug("ATOM XML format is corrupted ...");		    	     
	    	     return;
	         }
	     
	         var entriesLength = node.getElementsByTagName("entry").length;
	     
			 for (i = 0; i < entriesLength; ++i) {
				var entry = node.getElementsByTagName('entry').item(i);
			 	
				var title = entry.getElementsByTagName('title').item(0).firstChild.data;
			 	var published = entry.getElementsByTagName('published').item(0).firstChild.data;			
			 	var summary = entry.getElementsByTagName('summary').item(0).firstChild.data;
			 	var link = entry.getElementsByTagName('link').item(0).getAttribute("href");
			 	
				output += '<hr><p><a target="_blank" href="' + link +'">' + title + '</a><br/>' + 
					      '<span class="smaller">' + published + '</span><br/>' + 
					      summary +
					      '</p>';
			 }
			 
		     document.getElementById(resultPanelID).innerHTML = output; 	    	
         },
         error: function(error, ioArgs){		         
	         dojo.byId(resultPanelID).innerHTML = "Error loading atom feed";
	         console.debug("failed xhrGet for ATOM URL: ", error, ioArgs);	         
    	 }
	});
});	
</script>

<div id="resultPanel"></div>

The code listing gets all the <entry> elements in the ATOM feed then gets some of the child elements of the <entry> element which are the <title>, <published>, <summary>, and <link> elements and then displays their values in the "resultPanel" DIV element.

Parsing RSS feed

The next code listing is an example which loads and parses the RSS feed from the "rss.xml" file that contains an RSS XML.

<script type="text/javascript">
dojo.addOnLoad(function() {
	  var resultPanelID = "resultPanel";
	  
	  // Parse Rss Feed
	  dojo.xhrGet({
	     url: "rss.xml",
	     preventCache: true,
	     handleAs: "xml",
	     load: function(xmlDoc, ioArgs){		 
	         var i = 0;
	         var output = "";
	      
	         var node = xmlDoc.getElementsByTagName("channel").item(0);
	     
	         if (node == null) {
		         console.debug("RSS XML format is corrupted ...");	  		    	     
	    	     return;
	         }
	     
	         var entriesLength = node.getElementsByTagName("item").length;
			 
			 for (i = 0; i < entriesLength; ++i) {
				var entry = node.getElementsByTagName('item').item(i);
			 	
				var title = entry.getElementsByTagName('title').item(0).firstChild.data;
			 	var published = entry.getElementsByTagName('pubDate').item(0).firstChild.data;			
			 	var description = entry.getElementsByTagName('description').item(0).firstChild.data;
			 	var link = entry.getElementsByTagName('link').item(0).firstChild.data;
			 	
				output += '<hr><p><a target="_blank" href="' + link +'">' + title + '</a><br/>' + 
					      '<span class="smaller">' + published + '</span><br/>' + 
					      description +
					      '</p>';
			 }
			 	
		     document.getElementById(resultPanelID).innerHTML = output; 	    	
       },
       error: function(error, ioArgs){	         
	         dojo.byId(resultPanelID).innerHTML = "Error loading Rss feed";
	         console.debug("failed xhrGet for Rss URL: ", error, ioArgs);	  	         
  	   }	  
	});
});	
</script>

<div id="resultPanel"></div>

The code listing gets all the <item> elements in the RSS feed then gets some of the child elements of the <item> element which are the <title>, <pubDate>, <description>, and <link> elements and then displays their values in the "resultPanel" DIV element.

Ajax Error Handling

August 18, 2012 in Ajax, JavaScript, Web 2.0

In Order to return an Ajax error from the server, you need to set the response status to 500, For example if you are working with Java Servlets, your Java Servlet will return the error as follows:

public class AjaxServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		try {
			// Do whatever you want to do
		} catch (Exception exception) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	                response.getWriter().write(exception.getMessage());
	                response.flushBuffer();			
		} finally {
			// Clean up ...
		}
	}
	
}

In the client side, you can get the server error message (after checking that the readyState of the XML HTTP Request (XHR) is 4, and the status of the XHR object is 500) from the responseText of the XHR object.

If you are using a JavaScript framework (the Dojo for example): In the Dojo xhrPost API, in order to get the error message, you can get it from the ioArgs parameter of the error callback as follows:

dojo.xhrPost( {
	url: 'service URL',
	content: {},
	handleAs: 'text',
	load: function(response, ioArgs) {
		// Do something
	},
	error: function(response, ioArgs) {
		alert("Failed while doing the operation: " + ioArgs.xhr.response);
	}
});

Using the ioArgs.xhr.response, you can get the full error message from the server response, you can also get the status code from the ioArgs.xhr.status.

I wish that this advice can be useful for you in order to make Ajax error handling correctly.

Skip to toolbar