Posts Tagged ‘jParse post processing’

Using jParse to post-process an XML feed

Monday, October 24th, 2011

I have used jquery to parse XML in the past for simple tasks. But rewriting the same code every time gets tedious and cumbersome. So I have resorted to using jParse – which is a freely available plug-in especially made for this task.

The plug-in works great straight out of the box and you can even customize the output to your heart’s content.  Simple usage script below:

function start(){
jQuery('#jparse-meta').html('<img alt="Content Loading" src="ajax-loader.gif" />');
}
function finish(){
jQuery('#jparse-meta').remove();
}
$(function(){
$('#ajax-cont').jParse({
ajaxOpts: {url: 'kyle-rush-feed.xml'},
elementTag: ['title', 'link', 'description'],
output: ' <div><h4><a href="jpet01">jpet00</a></h4><p>jpet02</p></div>',
precallback: start,
callback: finish
});
});

HTML for the above script is:

<div id="jparse-meta" style="text-align: center; margin: 15px 0 0 0;">
<p><a href="//http://www.benjamingaw.com/blog">Read my Blog</a></p>
</div><!--/#jparse-meta-->
<div id="ajax-cont"></div><!--/#demo-cont-->

Simple, isn’t it? However, the project I was working on required a little bit more flexibility. As it is a feed that may at times, return nothing. So how do you display default text if the RSS/XML feed is empty? I have looked around for an answer to this and found nothing on Google, so I have to write a simple snippet to address this issue.

For my purposes, the code will lie within the finish function, as this is the callback function once jParse finishes running (see the line of code – callback: finish). And here is the code snippet I added to the finish function to display “No entries. Pls. check back later.”

function finish(){
jQuery('#jparse-meta').remove();
if ($('#ajax-cont').html() == 0) {
$('#ajax-cont').append('<h4>No entries</h4><p>Pls. check back later</p>');
}
}

And that’s it, if the XML doesn’t have any entries, it will show that line of text instead of a blank space.