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 » 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 – Random strings/passwords will display here. Load objects used for random string generation into the “Object Input Box” above. Objects above can be characters, words, sentences, etc. Test by clicking the “Generate random strings” 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 […]]]></description>
<content:encoded><![CDATA[<p>Output Box – Random strings/passwords will display here.<br />
Load objects used for random string generation into the “Object Input Box” above. Objects above can be characters, words, sentences, etc.<br />
Test by clicking the “Generate random strings” 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.
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 />' +
'' +
'<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:
''
^-- 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
You wrote doccument instead of document in your $(doccument).ready.
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.
Related
I am developing an application that uses loops to create a desired output; here from number 1 to 50. I am using a for loop and uses the concatenation method to show the looped numbers. But then the debugger in the browser is saying that I have written an unbalanced tree.
Here is the error:
An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
Here is the code:
<script type="text/javascript">
for(i=1;i<=50;i++){
document.write(""+i+"");
}
</script>
Note: The links I am creating use an id attribute to link somewhere exactly on the page.
Thanks for help.
It's a warning. It happens in Firefox 4 and later.
From MDN: Optimizing your pages for speculative parsing:
However, in Firefox 4 and later the HTML parser also runs the HTML tree construction algorithm speculatively. The upside is that when a speculation succeeds, there's no need to reparse the part of the incoming file that was already scanned for scripts, style sheets and images. The downside is that there's more work lost when the speculation fails.
[...]
Speculative tree building fails when document.write() changes the tree builder state such that the speculative state after the </script> tag no longer holds when all the content inserted by document.write() has been parsed. However, only unusual uses of document.write() cause trouble. Here are the things to avoid:
[...]
Don't write unbalanced trees. <script>document.write("<div>");</script> is bad. <script>document.write("<div></div>");</script> is OK.
The solution is to write the missing single closing quote.
<script type="text/javascript">
for(i=1;i<=50;i++){
document.write("<a href='page.html#"+i+"'>"+i+"</a>");
}
</script>
You have missed out an single quotes.
Try running with below:
for(i=1;i<=50;i++){
document.write("<a href='page.html#"+i+"'>"+i+"</a><br/>");
}
Be careful while using single and double quotes.
Even if you document.write(...) a balanced tree, for example document.write('<span>X</span>'), then you still can get the same error message.
One possible explanation is that you execute that JS code not in the body but in the head of the html, writing something that cannot occur in the head.
For example:
Wrong:
<html>
<meta charset="UTF-8">
<script>
document.write('<span>X</span>');
</script>
</html>
Good:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
document.write('<span>X</span>');
</script>
</body>
</html>
The widget I'm making uses Open Graph tags and I'm running into a complication when it comes to the "og:image" meta tag. I stripped out the rest of the irrelevant code, but this is what is causing the problem:
<?xml version="1.0" encoding="UTF-8"?>
<HTMLWidget>
<parameters>
<file name="ogImage" label="Image"/>
<!-- This enables the user to upload an image-->
</parameters>
<headHTML>
<meta property="og:image" content="{param_ogImage}" />
</headHTML>
</HTMLWidget>
The code that this will output is:
<meta property="og:image" content="/assets/example-image.png"/>
Facebook debugger will then say:
Object at URL
'http://www.example.com/' of type 'website' is invalid because the given value
'/assets/image.png' for property 'og:image:url' could not be
parsed as type 'url'.
So, my question is, is there a way to automatically grab and place the domain name in front of the {param_ogImage} content? Is it possible to use something like this to accomplish this task?
<script>
function myFunction() {
var x = document.domain;
document.getElementById("demo").innerHTML = x;
}
</script>
Not with current mucow's (version 3). This does appear to be something that is being added in the future version.
Goal:
To sum it up, I'm trying to replace an excel spreadsheet. I'm creating an application that will run in IE9, but does not connect to the internet or an intranet (I know, I know. Just bear with me. If you're curious read more below). It needs to use CRUD (create, read, update, and delete) methods on a set of data that changes daily. The dataset must persist even when the browser is closed.
Question:
What options are available, using javascript and html, for storing data on the local computer the web page is accessed on? I'm doing this at work, so there will be no server-side to this. I also will not be able to install any software on the computer, although I can download javascript plugins. The webpage will be loaded from a file on the computer, using Win 7 and IE9.
Background:
This deserves an explanation. I use an excel spreadsheet to track a set of data that changes daily. I'm learning HTML and javascript, and I can create a much better (and easier to use) solution as a webpage. I can create the UI / UX, but I'm having a difficult time figuring out how to store the data on the local computer. Any good suggestions?
Attempts:
Unfortunately, it seems localStorage is not an option. I'm attempting to use jStorage, but I've been running into problems there, also. A similar set of problems has been encountered using simpleStorage.
Thank you for considering, please let me know if any more info is needed, or if I need to clarify something.
Addendum:
Localstorage, and other forms of HTML5 storage, do not work. Officially it does, unofficially it is very buggy. See blog post here, and SO answer here. Either way, with the following simple code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Backlog Tracker</title>
<script src="jquery-2.1.1.min.js"></script>
<script src="backlog_localstorage.js"></script>
</head>
<body>
</body>
</html>
and javascript (ref as "backlog_localstorage.js" above):
$(document).ready(function(){
$("body").append("<button>Try It</button>");
$("button").click(function(){
localStorage.setItem("key1", "Hello");
console.log(localStorage.getItem("key1"));
});
});
... I get the following error: "SCRIPT5007: Unable to get value of the property 'setItem': object is null or undefined" on the line localStorage.setItem("key1", "Hello");
HTA (which is really just an html file with one extra tag and a different file extension) is one possible solution for windows users:
Important: Save as demo.hta to run on windows as an app
<!DOCTYPE html>
<html> <!-- some parts lifted from
http://msdn.microsoft.com/en-us/library/ms536496(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms536473(v=vs.85).aspx
-->
<head>
<title>State Saving Demo</title>
<hta:application id="App"
application="yes"
applicationname="demo"
icon="calc.exe"
border="thin"
caption="yes"
sysmenu="yes"
showintaskbar="yes"
singleinstance="yes"
sysmenu="no"
maximizeButton="yes"
minimizeButton="yes"
navigable="no"
scroll="yes"
contextmenu="no"
selection="no"
windowstate="normal" >
<!-- Use Internet Explorer 10 Standards mode (to use JSON, CSS3, etc...) -->
<meta http-equiv="x-ua-compatible" content="IE=10">
</head>
<body onload=loadMe() >
<h1 id=h1>Command-line args: </h1>
<h3>Persisted Text</h3>
<textarea rows=20 cols=100 id=mydata onchange=saveMe() >
You can change me and i won't forget!
</textarea>
<script>
document.title+=" - Today is " + Date(); // task/title bar demo
h1.innerHTML+= JSON.stringify( App.commandLine ); // optional invocation info here (much like a real app)
// app-specific custom code:
FILENAME="state.txt";
function saveMe(){save(FILENAME, mydata.value); }
function loadMe(){mydata.value=load(FILENAME) || mydata.value;}
// generic utils:
function load(filename) { //IE FSO file Loader
var file,
text="",
fso= new ActiveXObject('Scripting.FileSystemObject');
try{
file = fso.OpenTextFile(filename, 1, false);
text = file.readAll();
file.Close();
}catch(y){}
return text;
}
function save(filename, sData){ //IE FSO file Saver
var file,
fso = new ActiveXObject('Scripting.FileSystemObject');
file = fso.CreateTextFile(filename, 2, false);
file.write(sData);
file.Close();
return file;
}
</script>
</body>
</html>
I recently re-discovered HTAs, and they are not half bad. I don't think I would want to distribute and maintain them, but HTA's are an easy way to make simple desktop app using HTML, CSS, and JS. Its nice not to have to build anything to "recompile" the app after changes are made. saves a few steps compared to node-webkit, packaged apps, air, cordova, etc, but HTA's have a major downside: they only work on windows afaik...
Looks to me like you can use LocalStorage, the big question is how are you trying to store it? You can easily store an object/array into LocalStorage, and that object/array can be your data, then JS can output this into a table. If you're looking to store actual files then you're looking at something more like an ActiveX plugin.
http://caniuse.com/#search=localstorage
Alternatively if you have internet access through a desktop or a phone you can put this on Google Drive. This would be far easier than reinventing the wheel.
I'm trying to encode the £ sign in an external JS file but I keep getting '%EF%BF%BD'. Here's the code in its simplicity:
alert(encodeURIComponent("£"));
The same alert gives me '%C2%A3' on the HTML page that is calling the external JavaScript file. The HTML page has the following character set:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
And I've defined the character set for the external JS file too:
<script type="text/javascript" src="/js/share.js" charset="utf-8"></script>
How can I force the external JavaScript file use UTF-8 encoding?
Fixed the problem by creating a blank JS file with UTF-8 encoding, copying the code in from the original file and replacing the old file with the new file.
ef bf bd is the replacement character - what a browser uses if it does not have the given character in its font.
If it renders correctly here, it looks like this: �
My guess would be that whatever font you're using does not support the British pound symbol £
Could you add a link to the page you're using or a demo?
Use UTF encoded character
alert("\u00A3");
On jsfiddle
UPDATE: I am still unsure as to what your problem is, but here is a further example.
HTML
<div id="out"></div>
Javascript
var link = "http://somewhere.com",
tweet = "£££££€€€€€€€",
x = 'anchor';
document.getElementById("out").innerHTML = x;
alert(decodeURIComponent(x));
On jsfiddle
As I suggested in the comments, you should construct a jsfiddle to demonstrate the issue you are having if the above is not the solution that you are looking for.
I am having trouble displaying some jason from a page.
The data is there but I think it might have to do with this line:
document.write(fbResults.cats[0].title);
Here is the full html source:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://mydomain.com/api/get_cats', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
</script>
</head>
<body>
</body>
</html>
And here is the data that it's reading:
{"cats":[
{"id":"1","title":"mytitle1","colour":"#EE297C"},
{"id":"2","title":"mytitle2","colour":"#EE412F"},
{"id":"3","title":"mytitle3","colour":"#F5821F"},
{"id":"4","title":"mytitle4","colour":"#00AEEF"},
{"id":"5","title":"mytitle5","colour":"#00B495"},
{"id":"6","title":"mytitle6","colour":"#006476"}
]}
It is not displaying anything on the page.
On firebug console I get this error:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
No traces of the json data there
What I'm I doing whong?
You shouldn't document.write after the page has loaded (which is certainly the case here).
If you want to write it to the page, you'll need to create HTML and append it. Just replace the document.write:
$('body').append('<p>'+fbResults.cats[0].title+'</p>');
Update:
Your example makes a fully qualified URL call. Is that server the exact same one that you're running the page from? If it isn't the XHR will just eat the request (and sometime not tell you). If you need to go cross domain, you'll need to use JSONp. If you're attempting to run this locally while pulling data from the net, it'll break.
Try this
$.each(fbResults.cats,function(index,item){
document.write(item.title);
});
Working sample : http://jsfiddle.net/zWhEE/8/
its seems work for me please check this
http://jsfiddle.net/TxTCs/1/