Load and Parse a JSON file in local system using jQuery - javascript

I am new to scripting languages. I have googled for loading and parsing the JSON file using jQuery. I have taken the help of those links that I got from Stack Overflow.
I have this JSON file named new.json .
{ "a": [
{"name":"avc"},
{"name":"Anna"},
{"name":"Peter"},
{"Folder": "ABC", "name":[
{"name":"John"},
{"name":"Anna"},
{"Folder":"XYZ", "name":[
{"name":"fdgh"},
{"name":"hdfghh"},
{"Folder":"JKL", "name":[
{"name":"gdfgdfgggggg"},
{"name":"hddddddddddddddddddddddddddddh"},
{"Folder":"PQR", "name":[
{"name":"gddddddg"},
{"name":"ddhh"}
]
}
]
}
]
}
]
}
]
}
And this is my code jQuery/JavaScript code to load the new.json file. I have written my Code inside the <script> tag.
<script src="jquery-3.1.0.js"></script>
<script type="text/javascript" language="javascript" src="C:\Users\Girish\Desktop\new.json"></script>
<script type="text/javascript">
var out="<ul>";
var j=0;
function functionName(event) {
$('li[id^="foo"]').click(function(e){
e.stopPropagation();
var x = $(this).last().find(' > ul').clone().find('ul').remove().end();
$('#list').html(x);
$("#list .hide").show();
});
}
$(document).ready(function() {
$('li[id^="foo"]').each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});
function read(obj){
for(var i = 0; i < obj.length; i++)
{
if(obj[i].Folder)
{
var name = "foo"+ ++j;
var name2 = "<li id=" + name + ">";
out = out+ name2 + obj[i].Folder + "<ul>";
document.getElementById("tree").innerHTML = out;
read(obj[i].name);
out=out+"</ul></li></ul>";
}
else
{
var name2 = "<li class=\"hide\">";
out = out+ name2 + obj[i].name;
document.getElementById("tree").innerHTML = out;
out=out+"</li>";
}
}
}
function show()
{
//read(a)
var myItems;
$.getJSON('new.json', function(data) {
myItems = data.a;
read(myItems)
});
}
</script>
and this is <body> tag.
</div>
<div id="list"></div>
When I am running this code on Google Chrome. It is giving this error
jquery-3.1.0.js:9392 XMLHttpRequest cannot load file:///C:/Users/Girish/Desktop/new.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. on console. I have googled this error, I have found some links that says that run the same file on Mozilla Firefox.
The same code I am running on Mozilla Firefox, It is not giving any error. It is showing Items in #tree div. but when I am clicking on any item in tree div. It is not showing its child elements in #list div.
Now I want to load the json file on both Chrome and Firefox. How can I fix the above error?
Why child items are not showing in list div when clicking on any item in tree div?
Thanks

This has nothing to do with JQuery. You simply can't access local files if you're running a web page locally (with file:/// at the beginning of the URL). It violates the security model of locally run pages.
The error you're receiving is related to something called CORS (cross origin resource sharing) and is a widely used security mechanism to only allow client-side browser applications on the same domain to access resources or APIs. Anything outside the trusted CORS policy gets rejected. In the case of local web pages, files are considered to be outside your origin; Your browser essentially considers your hard drive to be on a different domain. Otherwise, malicious scripts would be able to easily access your local files by simply guessing paths to access.
To fix this, you need to use some kind of development server (or full blown web server) so that your page can be locally hosted. Then you can access your page via http://localhost/ or your local IP address, usually http://127.0.0.1/.
Some examples of development servers that can host static files:
Fenix Web Server looks like a good option for static hosting
If you have Python installed python -m SimpleHTTPServer will start a server on http://localhost:8000/ in whatever folder you start it in
Mongoose seems to have nice web-based management console
Basically any search for static web server (with your operating system) should find a lot of simple options.

Related

Installing firefox extension on a web site

I have created an extension for mozilla firefox. Now, I'm trying to distribute the extension on an simple web site. I generate a sha1 hash code from an online generator. This is the code I have in my web site:
<script type="application/javascript">
function install (aEvent)
{
for (var a = aEvent.target; a.href === undefined;) a = a.parentNode;
var params = {
"Foo": { URL: aEvent.target.href,
Hash: aEvent.target.getAttribute("hash"),
toString: function () { return this.URL; }
}
};
InstallTrigger.install(params);
return false;
}
</script>
<a href="c:/grouAndUsersWorkSpace/MozillaAddon/createtab.xpi"
hash="sha1:a7093a2afe1a53fde114a4a7dcb3e15e57862642"
onclick="return install(event);">Install Extension!</a>
the path of the url is local. And as a result when I start the application I got "The add-on could not be downloaded because of a connection failure on localhost".
I changed the path of the url to be: file://c:/grouAndUsersWorkSpace/MozillaAddon/createtab.xpi and with this nothing happens.
I have two questions:
1. Is that a good way to generate a hash code?
2. What should cause that connection failure?
1) I prefer to use the CHK Checksum Utility to generate checksums.
2) I don't have access at the moment to verify it, but have you tried serving the extension with Apache or similar?
Edit
Since you used a local file, you'll need a 3 slashes instead of 2 : file URI scheme .
Tested it both ways, they both work.

Do we need a web server (like Apache) to access a .json file?

I was trying to read an info.json file, using the jQuery API. Please find the code below, which is part of test.html.
$.getJSON('info.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
The test.html file resides on my local machine and when I try to open it in the browser, the Ajax call is not getting triggered and the info.json file is not read.
Is it not working because I don't have a web server? Or am I doing anything wrong in the code? (I don't see any errors in the Firebug console though).
Thanks in advance.
You will always have to host your site from where you are making AJAX call. Otherwise it will throw this exception.
origin null is not allowed by access-control-allow-origin
Host your page on localhost server and I guess everything will work nicely.
While technically you don't need a web server for this, some of the libraries you use to abstract network access may not work with local files and some browsers don't let local files do a lot, so something like a little test web server for static files would be very useful for your development and testing.
Install a small webserver like http://jetty.codehaus.org/jetty/
easy to install, and small download ;)
By putting your JSON string into a text file and loading it in a iframe, you can extrapolate the data. (Most browsers can load .txt files in iframes.)
var frame = document.createElement("IFRAME"); //Create new iframe
var body = document.body;
frame.onload = function() { //Extrapolate JSON once loaded
data = JSON.parse(frame.contentDocument.documentElement.innerText); //Loads as a global.
body.removeChild(frame); //Removes the frame once no longer necessary.
}
frame.style.display = "none"; //Because the frame will have to be appended to the body.
body.appendChild(frame);
frame.src = "your JSON.txt"; //Select source after the onload function is set.

Issues in developing web scraper

I want to develop a platform where users can enter a URL and then my website will open the webpage in an iframe. Now the user can modify his website by simply right clicking and I will provide him options like "remove this element", "copy this element". I am almost through. Many of the websites are opening perfectly in iframe but for a few websites some errors have shown up. I could not identify the reason so asking for your help.
I have solved other issues like XSS problem.
Here is the procedure I have followed :-
Used JavaScript and sent the request to my Java server which makes connection to the URL specified by the user and fetches the HTML and then use Jsoup HTML parser to convert relative URLs into absolute URLs and then save the HTML to my disk in Java. And then I render the saved HTML into my iframe.
Is somewhere wrong ?
A few websites are working perfectly but a few are not.
For example:-
When I tried to open http://www.snapdeal.com it gave me the
Uncaught TypeError: Cannot read property 'paddingTop' of undefined
error. I don't understand why this is happening..
Update
I really wonder how this is implemented? # http://www.proxywebsites.in/browse.php?u=Oi8vd3d3LnNuYXBkZWFsLmNvbQ%3D%3D&b=13&f=norefer
2 issues, pick any you like:
your server side proxy code contains bugs
plenty of sites have either explicit frame-break code or at least expect to be top level frame.
You can try one more thing. In your proxy script you are saving your webpage on your disk and then loading into iframe. I think instead of loading the page you saved on disk in iframe try to open that page in browser. All those sites that restirct their page to be loaded into iframe will now get opened without any error.
Try this I think it an work
My Proxy Server side code :-
DateFormat df = new SimpleDateFormat("ddMMyyyyHHmmss");
String dirName = df.format(new Date());
String dirPath = "C:/apache-tomcat-7.0.23/webapps/offlineWeb/" + dirName;
String serverName = "http://localhost:8080/offlineWeb/" + dirName;
boolean directoryCreated = new File(dirPath).mkdir();
if (!directoryCreated)
log.error("Error in creating directory");
String html = Jsoup.connect(url.toString()).get().html();
doc = Jsoup.parse(html, url);
links = doc.select("link");
scripts = doc.select("script");
images = doc.select("img");
for (Element element : links) {
String linkHref = element.attr("abs:href");
if (linkHref != "") {
element.attr("href", linkHref);
}
}
for (Element element : scripts) {
String scriptSrc = element.attr("abs:src");
if (scriptSrc != "") {
element.attr("src", scriptSrc);
}
}
for (Element element : images) {
String imgSrc = element.attr("abs:src");
if (imgSrc != "") {
element.attr("src", imgSrc);
log.info(imgSrc);
}
}
And Now i am just returning the path where i saved my html file
That's it about my server code

wget + JavaScript?

I have this webpage that uses client-side JavaScript to format data on the page before it's displayed to the user.
Is it possible to somehow use wget to download the page and use some sort of client-side JavaScript engine to format the data as it would be displayed in a browser?
You could probably make that happen with something like PhantomJS
You can write a phantomjs script that will load the page like a browser would, and then either take screenshots or use JS to inspect the page and pull out data.
Here is a simple little phantomjs script that triggers javascript on a webpage and allows you to pull it down locally:
file: get.js
var page = require('webpage').create(),
system = require('system'), address;
address = system.args[1];
page.scrollPosition= { top: 4000, left: 0}
page.open(address, function(status) {
if (status !== 'success') {
console.log('** Error loading url.');
} else {
console.log(page.content);
}
phantom.exit();
});
Use it as follows:
$> phantomjs /path/to/get.js "http://www.google.com" > "google.html"
Changing /path/to, url and filename to what you want.
Not with wget, as I doubt it includes any form of a JavaScript engine. However, you could use WebKit to process the page, and thus the output.
Using things like this as a base for how to get the content: http://situated.wordpress.com/2008/06/04/take-screenshots-of-a-website-from-the-command-line/

Cross-site XMLHttpRequest

I want to provide a piece of Javascript code that will work on any website where it is included, but it always needs to get more data (or even modify data) on the server where the Javascript is hosted. I know that there are security restrictions in place for obvious reasons.
Consider index.html hosted on xyz.com containing the following:
<script type="text/javascript" src="http://abc.com/some.js"></script>
Will some.js be able to use XMLHttpRequest to post data to abc.com? In other words, is abc.com implicitly trusted because we loaded Javascript from there?
Will some.js be able to use XMLHttpRequest to post data to abc.com? In other words, is abc.com implicitly trusted because we loaded Javascript from there?
No, because the script is loaded on to a seperate domain it will not have access...
If you trust the data source then maybe JSONP would be the better option. JSONP involves dynamically adding new SCRIPT elements to the page with the SRC set to another domain, with a callback set as a parameter in the query string. For example:
function getJSON(URL,success){
var ud = 'json'+(Math.random()*100).toString().replace(/\./g,'');
window[ud]= function(o){
success&&success(o);
};
document.getElementsByTagName('body')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = URL.replace('callback=?','callback='+ud);
return s;
})());
}
getJSON('http://YOUR-DOMAIN.com/script.php?dataName=john&dataAge=99&callback=?',function(data){
var success = data.flag === 'successful';
if(success) {
alert('The POST to abc.com WORKED SUCCESSFULLY');
}
});
So, you'll need to host your own script which could use PHP/CURL to post to the abc.com domain and then will output the response in JSONP format:
I'm not too great with PHP, but maybe something like this:
<?php
/* Grab the variables */
$postURL = $_GET['posturl'];
$postData['name'] = $_GET['dataName'];
$postData['age'] = $_GET['dataAge'];
/* Here, POST to abc.com */
/* MORE INFO: http://uk3.php.net/curl & http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html */
/* Fake data (just for this example:) */
$postResponse = 'blahblahblah';
$postSuccess = TRUE;
/* Once you've done that, you can output a JSONP response */
/* Remember JSON format == 'JavaScript Object Notation' - e.g. {'foo':{'bar':'foo'}} */
echo $_GET['callback'] . '({';
echo "'flag':' . $postSuccess . ',";
echo "'response':' . $postResponse . '})";
?>
So, your server, which you have control over, will act as a medium between the client and abc.com, you'll send the response back to the client in JSON format so it can be understood and used by the JavaScript...
The easiest option for you would be to proxy the call through the server loading the javascript. So some.js would make a call to the hosting server, and that server would forward the request to abc.com.
of course, if that's not an option because you don't control the hoster, there are some options, but it seems mired in cross browser difficulties:
http://ajaxian.com/archives/how-to-make-xmlhttprequest-calls-to-another-server-in-your-domain
You could use easyXSS. Its a library that enables you to pass data, and to call methods across the domain boundry. Its quite easy and you should be able to use it.
There are many examples on the code.google.com site

Categories

Resources