As you already probably know, AJAX is a javascript technology providing us with an easy way of reading and/or parsing data from the server without using even a single line of server-side language in most of the cases, or as w3schools says – “AJAX is the art of exchanging data with a server, and update parts of a web page – without reloading the whole page.“. Although it can freely be used without any library, when using jQuery in our project, why not trying its AJAX functions as well?
What is shown in the current post is RSS file data parsing with the jQuery.ajax() method. As a sample XML I am using a RSS file, used in my Useful links repository. As the file is with ever changing (let’s hope expanding) content, I would not show its contents here, but instead – in the demo page.
Let’s start first with the code I am actually using in the page where I am editing the content of the RSS Feeds in the Useful links repository.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
var getXMLElement = function(url, element) { $.ajax({ type: "GET", url: url, cache: false; dataType: "xml", success: function(xml) { $(xml).find('item title').each(function() { if ( $.trim(element) == $.trim($(this).text()) ) { var nodeToEdit = $(this).parent(); var title = element; var description = nodeToEdit.find('description').text(); var link = nodeToEdit.find('link').text(); $("#title").val(title); $("#description").val(description); $("#link").val(link); } }); }, error: function(jqXHR, text, errorMsg) { alert("Error opening file - "+errorMsg); } }); } |
About the Ajax primer above
The function above takes url and element as arguments, where url is the path to the file, which we are about to open for parsing and would be passed to url parameter of the jQuery.ajax() method. The element is used for searching a string in the parsed file, but have in mind that the logic behind my search is a bit weak, as it would not work correctly if there are two or more equal “title” strings in the “item” nodes.
A bit over the RSS files
The obligatory nodes (tags) of a RSS file are title, link, description and at least one item for the actual content, where each item should have the title, link and description tags itself as well. More about the structure of a RSS file and other optional elements could easily be found on google. Now let’s go back to the Ajax calls.
The url parameters
What you need to know when opening files with Ajax is that the path for the URL parameter of each method is relative to the root of your server, no matter where the HTML or Javascript files actually are. Actually, you won’t be able to make an Ajax call to any other (web) server. Let’s observe for example the following structure: http://myDomainName.net/library/mainFeed.xml. To pass a relative path to the xml file as argument, you should use “/library/mainFeed.xml”.
jQuery.ajax() method parameters used in the first example
The other jQuery.ajax() parameters are type – the default one is “GET”, when also “POST”, “PUT” and “DELETE” are available, but the latter two are not supported by all the browser, according to the jquery ajax() documentation page. Setting cache parameter to false would force the browse not to cache the page and the dataType tells us how the returned data would be formatted. Success is a parameter, expecting a callback function to be executed by successful load, while callback “linked” to the error parameter would be executed by any errors loading the data. Both the functions could get data, textStatus and jqXHR as arguments, in the case above – xml argument passed to success represents the data, fetched from the file as xml object (because of the dataType: “xml”).
Traversing over XML-formatted data
Now, that was pretty much the basics, the actual parsing of the data depends entirely on you, I would only give you a few (let’s hope useful) examples. When formatted as xml, the returned data could be traversed with jQuery.find() method, as you can see from the example above. Using it with the current “items title” argument would give us a set of title tags, children of the item tags. Iterating over find(“title”) would give us pretty much the same, only with the channel tag’s title. As you can see, when formatted as xml, the data returned by the ajax call would be easily manipulated like any other proper DOM Object.
If we need to return the data, fetched by the ajax call, instead of processing it in a callback function, according to my research on the matter, one thing is obligatory, namely:
1 2 3 4 5 |
$.ajax()({ ... async: false, ... ;}); |
Now, lets substitute the dots above with the actual code from the demo page:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
var getXML = function(url) { var xmlDoc = null; $.ajax({ type: "GET", url: url, dataType: "xml", async: false, success: function(xml) { xmlDoc = $(xml); }, error: function(jqXHR, text, errorMsg) { alert("The following error occured: "+errorMsg); } }); return xmlDoc; } function write(node, niveau) { // indention for better formatting var indent = " "; if (niveau == null) { niveau = 0; } for (var i=0; i<niveau; i++) { indent += indent; } // actual implmentation $("#recursive").append("<br />"+indent+"["+node.get(0).nodeName+"]"); if (node.children().length) { niveau++; node.children().each(function() { write($(this), niveau); }); } else { $("#recursive").append(node.text()/*+"[\\"+node.get(0).nodeName+"]"*/); } // Optional line - closes all the tags, but fucks up the formatting. (the indent should be somehow splitted) //$("body").append("[\\"+node.get(0).nodeName+"]<br />"); } $(document).ready(function() { var link = "/faddap/categories/javascript.xml"; var xmlDoc = getXML(link); // Procesing by known structure xmlDoc.find('item').each(function(){ $(this).children().each(function(){ // this refers to xmlElement, while $(this) is a jQuery object $("#processing").append(this.nodeName+" - "+$(this).text()+"<br />"); }); }); // Simple recursive printing of all the nodeNames and nodeValues. write(xmlDoc); }); |
First have a look at the link variable on line 41 – the relative path used there is actually almost the same as the absolute one, which it corresponds to – “http://if-act.net/faddap/categories/javascript.xml”.
The getXML function
Now let’s go to getXML – the function which returns the fetched data, using the xmlDoc variable. Have in mind that $(xml) on line 9, is a jQuery object, representing the xml data. As everything else in the Ajax call here is pretty much the same as the code used in the Ajax code in the first primer, let’s go a bit down the code. Already having the XML Object, hold by the xmlDoc variable on line 42, we can traverse it using standard jQuery functions for traversing DOM elements.
The recursive write function
The recursive function write, shown above is just a basic primer for iterating over RSS document with unknown structure and does not cover namespaces, additional tag attributes and so on.
More on the matter
All the jQuery’s Ajax methods and functions
More on the XMLHttpRequest Call
w3schools Ajax tutorial
What I find so itneretsing is you could never find this anywhere else.
I found just what I was needed, and it was entreatining!
I love your site, but honestly tell you that you need more for him to monitor those who commented with your records.
Finally a person that puts some real work into a blog. I do like what you have done with the blog.
I do not even know how I finished up here, but I believed this submit was good. I do not recognise who you’re but definitely you are going to a well-known blogger in case you are not already 😉 Cheers!
Couldn’t have said it better myself.
I observed your blog using google and I must say, this is most likely one of the greatest nicely ready articles I have come across in a long time. I’ve bookmarked your site for more posts.
Acne home remedies
It is exactly like you read my ideas! You look as if understand a lot concerning this, really like you wrote it inside it or something. I do believe that you can do with some pics they are driving your message home somewhat, however besides that, it is good weblog..
I love your writing style. I hope you decide to update this blog often!
I’m extremely impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it’s rare to see a nice blog like this one these days..
I love your writing style. I hope you decide to update this blog often!
Couldn’t have said it better myself.
Awesome writing style!
I love reading this blog. Keep up the good work!
Awesome points! I am glad I found someone writing about this!
Awesome writing style!
Awesome writing style!
Great post!
Love your blog!
Anxiously been recently looking essentially everywhere you go at the specifics of this specific. Really thanks great deal.
Great post!
Awesome post! I will keep an on eye on your blog.
Awesome writing style!
I actually wanted to compose a small note to thank you for some of the pleasant secrets you are showing on this website.
Awesome post! I will keep an on eye on your blog.
I’d have to test with you here. Which isn’t one thing I usually do! I enjoy studying a put up that can make folks think. Also, thanks for allowing me to comment!
Love your blog!
It is really a nice and useful piece of information. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.
Hello. I absolutely required to leave a good swift commentary and inform you grasp that I’ve been reading your personal page for quite some time. Keep up the impressive work and I am going to be checking back again yet again relatively quickly.
Great post!
Hi there! Outstanding written piece! I am also a everyday targeted visitor in your site (like with abuser) of this web page in all honesty My spouse and i an effort. Me certainly not truly absolutely sure whether it is the suitable web-site to be able to question, yet you’ve got not any spam posts. We acquire comments every single day. Can simply everyone aid me? Really head over heels!
I went over this site and I think you have a lot of superb info, bookmarked (:.
Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! By the way, how can we communicate?
Valuable information. Lucky me I found your site by accident, and I am shocked why this accident did not happened earlier! I bookmarked it.
We are a group of volunteers and opening a new scheme in our community. Your website provided us with valuable information to work on. You have done a formidable job and our whole community will be grateful to you.
I simply want to tell you that I am very new to blogging and site-building and seriously savored you’re blog site. Likely I’m planning to bookmark your blog post . You definitely come with fabulous posts. Bless you for sharing your blog site.
I want to get across my love for your kindness supporting persons that need help with this one subject matter. Your personal dedication to passing the solution up and down ended up being certainly productive and has really enabled girls much like me to achieve their aims. Your entire interesting suggestions denotes a whole lot a person like me and a whole lot more to my office colleagues. Thanks a lot; from all of us.
I’m impressed, I have to say. Actually hardly ever do I encounter a blog that’s both educative and entertaining, and let me let you know, you could have hit the nail on the head. Your thought is excellent; the problem is one thing that not sufficient individuals are speaking intelligently about. I’m very joyful that I stumbled throughout this in my seek for one thing referring to this.
Hi, i think that i saw you visited my weblog thus i came to “return the favor”.I am attempting to find things to improve my site!I suppose its ok to use a few of your ideas!!
Whats up there admin, I mainly needed to firmly leave a quick comment to actually declare that I appreciated your specific piece of writing. Thanks!
You can definitely see your enthusiasm in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always follow your heart.
I think there’s an issue with the RSS feed here. Seems like a broken link to me?
I have read a few good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create such a wonderful informative site.
Thank you, I have been looking for details about this subject matter for ages and yours is the best I’ve discovered so far.
How to upload a wordpress backup on to a site?
Heya i am for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you helped me.
Awesome writing style!