2

I'm currently teaching myself some AJAX through jQuery.

I've written a straight forward get request to load in data from an xml file into a section with a class of container.

Here is my html file:

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>

<section class="container">

</section>


<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8" async defer></script>
<script src="xmlFeed.js" type="text/javascript" charset="utf-8" async defer></script>
</body>
</html>

I am using a local xml file after i created to dummy post on a WordPress site and got the feed.

Here is the xml file:

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    >

<channel>
    <title>Biz-Tech.ie &#187; Biz-Tech News</title>
    <atom:link href="http://www.biz-tech.ie/category/biz-tech-news/feed/" rel="self" type="application/rss+xml" />
    <link>http://www.biz-tech.ie</link>
    <description></description>
    <lastBuildDate>Sat, 11 Oct 2014 17:39:16 +0000</lastBuildDate>
    <language>en-US</language>
        <sy:updatePeriod>hourly</sy:updatePeriod>
        <sy:updateFrequency>1</sy:updateFrequency>
    <generator>http://wordpress.org/?v=4.0</generator>
    <item>
        <title>News</title>
        <link>http://www.biz-tech.ie/news/</link>
        <comments>http://www.biz-tech.ie/news/#comments</comments>
        <pubDate>Sat, 11 Oct 2014 17:39:16 +0000</pubDate>
        <dc:creator><![CDATA[Michael]]></dc:creator>
                <category><![CDATA[Biz-Tech News]]></category>

        <guid isPermaLink="false">http://www.biz-tech.ie/?p=170</guid>
        <description><![CDATA[Output Box &#8211; Random strings/passwords will display here. Load objects used for random string generation into the &#8220;Object Input Box&#8221; above. Objects above can be characters, words, sentences, etc. Test by clicking the &#8220;Generate random strings&#8221; button above to generate 10, 14 character, random strings from the default input objects. NOTICE: Tool uses Javascript method Math.random() pseudorandom generator to obtain [&#8230;]]]></description>
                <content:encoded><![CDATA[<p>Output Box &#8211; Random strings/passwords will display here.<br />
Load objects used for random string generation into the &#8220;Object Input Box&#8221; above. Objects above can be characters, words, sentences, etc.<br />
Test by clicking the &#8220;Generate random strings&#8221; button above to generate 10, 14 character, random strings from the default input objects.<br />
NOTICE: Tool uses Javascript method Math.random() pseudorandom generator to obtain random string. Do not use for critical random results.<br />
Privacy of Data: This tool is built-with and functions-in Client Side JavaScripting, so only your computer will see or process your data input/output.</p>
]]></content:encoded>
            <wfw:commentRss>http://www.biz-tech.ie/news/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>
        </item>
    </channel>
</rss>

And finally here is the ajax GET request along with a function to parse the xml into the container section in my html:

 $(doccument).ready(function() {
   $.ajax({
      type:"GET",
      url:"feed.xml",
      dataType:"xml",
      success:xmlParser
   });
});

function xmlParser(xml) {
   $(xml).find("item").each(function(){
      $("#container").append('<h3>'+ $(this).find("title").text()+'</h3><br />'
         '<a href="'+ $(this).find("link").text()+'></a>'
         '<p>'+ $(this).find("description").text()+'</p>'
         '<p><h5>Author: '+ $(this).find("dc:creator").text()+'</h5></p>'
         );
   });
}

The function isn't working and for the life of me I have no idea why as I can see an syntax errors. Any advice would be greatly appreciated. Thanks.

1
  • SCRIPT1006: Expected ')' xmlFeed.js, line 13 character 10 Commented Oct 12, 2014 at 10:22

3 Answers 3

5

A few problems with your code.

1). The way you are concatenate strings in javascript is not correct. Use this syntax:

   $(xml).find("item").each(function(){
      $(".container").append('<h3>'+ $(this).find("title").text()+'</h3><br />' +
         '<a href="'+ $(this).find("link").text()+'"></a>' +
         '<p>'+ $(this).find("description").text()+'</p>' +
         '<p><h5>Author: '+ $(this).find('dc\\:creator, creator').eq(0).text()+'</h5></p>'
         );
   });

Note + operator, it is used for string concatenation.

2). One more problem. You missed a closing quote in link construction string, which breaks HTML and hides all subsequent content:

'<a href="' + $(this).find("link").text() + '"></a>'
                                             ^-- add this guy here 

3). One more thing: your selector must be $(".container") since container is a class, not id.

4). And finally there is one more little detail about how you should retrieve dc:creator node. Since this node is namespaced you need to escape it like this:

.find("dc\\:creator")

However it still doesn't guarantee that it will work in all browsers. You probably should do something like this:

$(this).find('dc\\:creator, creator').eq(0)

You provide two selectors here. The second selector creator will work in Chrome, and the first (escaped) in Firefox.

5). Also just in case, doccument is a probably a typo, but anyway it should be document.

Demo: http://plnkr.co/edit/0Z2tJJ3JANtJq30CNUDD?p=preview

Sign up to request clarification or add additional context in comments.

3 Comments

I'm now getting a console error at the beginning of my xmlFeed.js .xmlFeed.js, line 1 character 1. SCRIPT5009: '$' is undefined
It means that jQuery is not loaded. Make sure it's goes before xmlFeed.js.
Thanks very much for taking the time to build the plunker demo. I copied pasted and renamed my files to match yours. I am still getting a console error. SCRIPT5009: '$' is undefined script.js, line 1 character 1
2

You wrote doccument instead of document in your $(doccument).ready.

2 Comments

I've updated the syntax to correct both your points to this: $(document).ready(function() { $.ajax({ type:"GET", url:"feed.xml", dataType:"xml", success:xmlParser }); }); function xmlParser(xml) { $(xml).find("item").each(function(){ $("#container").append('<h3>'+ $(this).find("title").text()+'</h3><br />' + '<a href="'+ $(this).find("link").text()+'></a>' + '<p>'+ $(this).find("description").text()+'</p>' + '<p><h5>Author: '+ $(this).find("dc:creator").text()+'</h5></p>' ); }); }
I am still getting this console error:'Uncaught SyntaxError: Unexpected string '
0

The key to your problem is "I am using a local xml file ...". If you look at your console I am pretty sure that you are getting an "Access-Control-Allow-Origin error". This is a browser model security problem. Have a read here if you need more info.

In short though Access-Control-Allow-Origin errors occurs when you call a Web Service such as do a GET request for an XML file, from a domain that is different from the one hosting your HTML page. In you case I believe that you are your HTML file is on your hard drive while the Web Service is called on the localhost.

For development purposes you can use this chrome plugin. That will work for now.

1 Comment

I apologies. I shouldn't have used the word local. I have all the file in the same folder on my desktop called New folder. the folder structure is: index.html, xmlFeed.js and feed.xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.