JQuery JSON data not displaying - javascript

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/

Related

Get the contents of a div element from one site to another

I have an argument in JS which holds pretty much the data. It's the server information to my server. It changes often, e.g 20/64 or 32/64. You get the point.
I am trying to get the contents of the data to go on an external site, however, when I try, it doesn't work.
To summerise, I have a div which holds the data, I want to get that data using JS and put it on an external site which isn't using the same domain or web server.
HTML FILE:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<div id="serverstats-wrapper"></div>
<script src="import.js"></script>
</body>
JS File:
$(document).ready(function(){
$.post("query.php", {},
function (data) {
$('#serverstats-wrapper').html (data);
});
});
var the_main = document.getElementById("serverstats-wrapper");
var the_data = the_main.textContent ? the_main.textContent : the_main.innerText;
I want to get the text from the html file to the js file then take it to an external website.
Tasid! This won't work! JS does't have such a technique implementet. To do so, you need node.js. This allows you to send the data over a socket to your other webserver.
It does't work difrently, because JS is executed direct on your PC.
You can grab data from another site; but you cannot inject JS code into another site. Here are some methods to retrieve html from another site: Include another HTML file in a HTML file

Unbalanced tree - JS Error

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>

Javascript include technique with dynamic SRC="url"

Is it possible (and a good idea) to pass dynamic data to a JavaScript include file via a hash url?
Such as:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
I am looking for an alternative to inline js in dynamically built pages:
<head>
<script src="scripts.js#x=123&y=456"></script>
<script>
$( document ).ready(function() {
pageInit(123, 456)
});
</script>
</head>
Is it a good idea to avoid inline js? How can you pass dynamic data without ajax which creates a needless roundtrip network request?
Note: The hash bang url is a special because the browsers ignore the hash portion of the url when checking the cache. At least for html files.
So all of these will reuse the index.html file it is in the cache:
index.html
index.html#x=123
index.html#x=345345
index.html#x=2342&y=35435
This same principle should hold true for javascript files. What I hope to achieve is to reuse the cache version of script.js from page to page.
Going to index.php, include this:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
Then going to fun.php include this
<head> <script src="scripts.js#x=898756465&y=5678665468456"></script> </head>
Then going to see.php include this
<head> <script src="scripts.js#session=887987979&csrf_token=87965468796"></script> </head>
From page view to page view, pass whatever info the page needs via the hash bang while at the same time reuse scirpt.js from cache.
So, is it possible to read the hash bang info from within the scirpts.js?
If the HTML file you are creating is dynamic, then just create inline JavaScript. Writing an include will just create an extra request from the browser, which you can avoid in the first place.
Edit:
just include a JavaScript file that reads the URL, you don't need to pass any variables (but of course, you also could):
$(document).ready(function() {
// pseudo code
hashbang = location.href.substr(location.href.indexOf('#') + 1);
if (hashbang.x && hashbang.y) {
pageInit(hashbang.x, hashbang.y);
} else if (hashbang.csrf_token) {
// do something else
}
});

Get raw content of Iframe

I want to use Jquery or javascript to get the raw content (mean everycharacter) of an Iframe. It sounds simple but I'm still struggling with finding the right way for it.
For now it is only a XML content in the Iframe though.
Here the code:
$(function() {
var xmlContent = $("#CFrame").contents().find("*").text();
// The magic
$('#SResult').xslt({xml: xmlContent, xslUrl: 'stylesheet/designSS.xsl'});
});
The html page
<form id="searchForm" method="GET" target="ContentFrame" action="http://125.235.8.210:380/search" onSubmit="processContent()">
.....
</form>
</div>
<div id="SResult">
</div>
<iframe id="CFrame" name="ContentFrame" frameborder="1" height="2000px" width="1000px" scrolling="no" src="stylesheet/test.xml"></iframe>
</body>
Thanks,
Disclaimer: I'll answer your question regardless of whether it is actually an elegant solution to your problem. Joseph seems to take that as the question. I would say he is probably right to do so.
It won't work trying to get the frame using mimetype text/xml. The browser will proceed and 'translate' the XML into HTML. That's why it doesn't sound so simple. This way it is actually impossible.
I present you with a simple work-around for this problem.
<html>
<head>
<script>
function getXmlContents() {
/*
Note: Because of security reasons, the contents of a document can be accessed from another document only if the two documents are located in the same domain.
http://www.w3schools.com/jsref/prop_frame_contentdocument.asp
*/
var iframeDocument = document.getElementById('greetingFrame').contentDocument;
if (iframeDocument == null)
return undefined;
var xmlContainer = iframeDocument.getElementById('xmlContainer');
if (xmlContainer == null)
return undefined;
return xmlContainer.innerText == null ? xmlContainer.textContent : xmlContainer.innerText;
};
</script>
</head>
<body>
<iframe id="greetingFrame" src="helloworld.html" onload="alert(getXmlContents())">
</iframe>
</body>
</html>
The contents of the XML are wrapped inside an HTML (helloworld.html):
<html>
<body>
<script id="xmlContainer" type="text/xml">
<?xml version="1.0" encoding="UTF-8"?>
<title>
Hello world
</title>
</script>
</body>
</html>
I've successfully tested this in Chrome, Firefox and IE.
Of course you would have to wrap your XML documents inside a HTML script tag as indicated above. The XML can also be wrapped in a different tag, if you'd like it rendered for example, but you'd have to encode the XML using html encoding. This needs to be done on the server-side. A very simple (php/ruby/python/etc) script would suffice.
If your XML resides on your domain, you are better off with AJAX, especially using the jQuery library, which parses it for you and make it ready for immediate manipulations.
If it does not live on your domain, then you can't access it via AJAX unless the remote server and your client's browser both support CORS.
You have options though:
If the remote server's API supports JSONP, use it instead of XML. Then you can use jQuery to retrieve JSONP data or roll your own script loader.
Or use your server to proxy the XML for you. Servers are not restricted to the Same Origin Policy. Create an API on your server that relays your form data to the remote server and retrieve the remote page - all as if your server was the browser. Then forward the results back to you.

jquery ajax parse response text

Ok this is really frusturating me because I've done this a hundred times before, and this time it isn't working. So I know I'm doing something wrong, I just can't figure it out.
I am using the jQuery .get routine to load html from another file. I don't want to use .load() because it always replaces the children of the element I'm loading content into.
Here is my .get request:
$(document).ready(function() {
$.get('info.html', {}, function(html) {
// debug code
console.log($(html).find('ul').html());
// end debug code
});
});
The file 'info.html' is a standard xhtml file with a proper doctype, and the only thing in the body is a series of ul's that I need to access. For some reason, the find function is giving me a null value.
In firebug, the GET request is showing the proper RESPONSE text and when I run
console.log(html);
Instead of the current console.log line, I get the whole info.html as output, like I would expect.
Any ideas?
You cannot pull in an entire XHTML document. You can only handle tags that exist within the <body> of an html document. Frustrating. Strip everything from info.html that isn't within your <body> tag and try it again.
There are other potential ways around this issue - check below "Stackoverflow Related Items" at the base of this response.
From the Doc: (http://docs.jquery.com/Core/jQuery#htmlownerDocument)
"HTML string cannot contain elements that are invalid within a div, such as
html, head, body, or title elements."
Stackoverflow Related Items:
Simple jQuery ajax example not finding elements in returned HTML
What is the best practice for parsing remote content with jQuery?
I know this is an old post but I've been having the EXACT same frustrating problem for a couple of hours and have found a solution. For me what actually worked was to have the html content wrapped with a form tag.
So having the following html source:
<html>
<head>
<body>
<form>
<div id="content">Some Stuff</div>
</form>
</body>
</head>
</html>
With this jquery snippet should work:
var callback = function (data) {
alert($("#content", $(data)).html());
};
$.get(url, null, callback, null);
Hope this helps...
I have found this being pretty clean solution:
var elementInResponse = $("<div>").html(responseText).find(selector);
Wanting to do the same thing and knowing that JQuery load(..) does it, I had a look in the code. While you can't turn a complete html response directly into a JQuery object, you can append it to one so:
function(data, textStatus, xhr) {
$(target).html(jQuery("<div>").append(data).find("#snippet"));
// Create a dummy div to hold the results,
// inject the contents of the document into it,
// Locate the specified elements
}
The response from the server that goes into data is like:
<! doctype ... >
<html>
<head>
...
</head>
<body>
<div id="snippet">
<p>Some content here that we are interested in</p>
</div>
</body>
</html>
Try including whole body within a <div> tag, e.g. <body><div>content</div></body>.

Categories