$.getJSON executes the error callback - javascript

I have a jQuery function that gets data from JSON file but I just can't get it to work. I am developing in Brackets editor and when I open site in their live preview everything works great. But when I open html file locally, $.getJSON.error is executed instead of normal $.getJSON
function loadJson(e)
{
$('.images').fadeOut(300);
var jsonURL = "../../../images.json";
var txt = $(e.target).text();
setTimeout(function ()
{
$('.images').empty();
$.getJSON(jsonURL, function(json)
{
var imgList = "";
$.each(json[txt], function ()
{
imgList += '<div class="image_container reference">
<a href="' + this.imgPath + '">
<img src="' + this.imgPath + '"/>
<div class="overlay">
<span>' + this.name + '</span>
</div>
</a>
</div>';
});
$('.images').append(imgList);
}).error(function(json) { alert("error"); });
}, 300);
$('.images').fadeIn(300);
}
Function gets clicked item label, matches that with array name in the JSON file and then respectively appends those images to a container. It is working as supposed when I run it in Brackets live preview so I really don't know what is going on?

But when I open html file locally, $.getJSON.error is executed
Browsers take security very seriously. When working locally, Chrome will block any Ajax request to a local file. Firefox will only allow you to do so if the requested file is in the same folder (or deeper) than you HTML page.
In short, either place the JSON file in the same folder and use Firefox, or install a local server.
WAMP Server (Windows) is what I use. You will be working locally, but you will be accessing your pages via the http:// protocol (localhost) instead of the file:// protocol. That should fix it! Mac users can install MAMP.

Related

Load and Parse a JSON file in local system using jQuery

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.

Google Apps Script, function to return text as hyperlink

I have a Google Apps Script function SearchFiles() which returns the download urls depending on the keyword the user provides. It is something like this:
function SearchFiles(inputValueFromUser) {
var searchFor ='title contains "' + inputValueFromUser + '"';
var searchForAbsString = inputValueFromUser + '.pdf' ;
//The Rest of the Code goes here
if(file.getName() == searchForAbsString){
downloadURL = "https://drive.google.com/uc?export=download&id=" + fileId;
arryOfUrls.push(downloadURL);
};
};
Logger.log('arryOfUrls: ' + arryOfUrls);
return arryOfUrls;//.toString(); //Send array of download urls back to client side JavaScript
};
The function is returning arryOfUrls in plain text.
1) How can it be sent in hyperlink form?
2) Is it possible to open the URL automatically(start download immediately) as one clicks the respective button( on Index.html) to get the link?
No it can't be sent as a hyperlink directly (at least not as far I know). But you can have the HTML information embedded into the string (like <a href=downloadUrl>...</a>"). This can be interpreted on the client side as a link.

403 Error using JavaScript to access folder

In a .Net Web Forms project am trying to use JavaScript to display all images in a folder. Using the following script gives me a 403 error
<script>
var dir = "fullimages/";
var filext = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + filext + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http:///", "");
$("body").append($("<img src=" + dir + filename + "></img>"));
});
}
});
</script>
But I am not quite sure why? I have checked around the site and found the following suggestion 403 forbidden error while getting javascripts under root folder. In my case JS is not on the list of handlers.
If I have got this right your trying to run Javascript on the server side. Are you using any particular framework, node JS for example?
Secondly what server architecture are you running, windows (IIS) / linux (APACHE, N GINX) etc...?
From having a brief read of your linked question, have you tried moving this script into the fullimages directory and then request that?

Load another page in jquery tooltip

My html code is:
<div class="ui-widget photo">
<div class="ui-widget-header ui-corner-all">
<h2>St. Stephen's Cathedral</h2>
<h3>Vienna, Austria</h3>
</div>
<div id="result"></div>
</div>
My Javascript code is:
$(function () {
$(document).tooltip({
items: "[href]",
content: function () {
var element = $(this);
if (element) {
var text = element.text();
var link = element.attr('href');
// alert(link);
return "<img class='map' alt='" + text +
"' src='http://maps.google.com/maps/api/staticmap?" +
"zoom=11&size=350x350&maptype=terrain&sensor=false&center=" +
"Vienna, Austria" + "'>";
}
}
});
});
This thing is given here :
jQuery tooltip
But Now I want to load another page from another url say : www.google.com in this tooltip.
what I am doing is:
I am putting .load() function in this content section so that I can get response html and return it into the tooltip
Here is my code but its not working I am getting nothing in response ...
$(function () {
$(document).tooltip({
items: "[href]",
content: function () {
$('#result').load('http://stackoverflow.com/', function (response, status, xhr){
var responseText = response;
});
var element = $(this);
if (element) {
var text = element.text();
var link = element.attr('href');
// alert(link);
return responseText;
}
}
});
});
$.load('http://stackoverflow.com');
Won't return anything because you're trying to load another web site. That's against how AJAX works.
From jQuery docs:
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted.
It allows the user to load a file on the same domain, not external ones, for security reasons.
If you observe this fiddle with firebug opened you can see that the call will return header 200 OK but will not load anything due to these restrictions.
To achieve what you want you could make a local file that fetches the desired page, then make an ajax call to it, instead of a directly calling the web site.
A simple example of using local php file to get the page.
Create a local file, I'll call it foo.php
<?php
echo file_get_contents($_GET['url']);
// this will echo contents of given url
?>
Mind, this is only an example code and is not for serious use
Then call it like this
$("#container").load("foo.php?url=google.com");
This is because you are trying to make a CORS (Cross Origin Resource Sharing) request.
And because of security concerns such requests are not entertained by browsers and servers unless the server returns Access-Control-Allow-Origin header with the requesting domain acceptable to it.
To know when does CORS come into play read this: http://en.wikipedia.org/wiki/Same_origin_policy#Origin_determination_rules
To know more about CORS read the following article http://www.html5rocks.com/en/tutorials/cors/.
To test if the server supports CORS you can use the following website: http://client.cors-api.appspot.com/client
An alternative would be to make a PHP proxy on your server and then make a CORS request through that proxy.
Here is a tutorial for creating your own PHP proxy http://jquery-howto.blogspot.in/2009/04/cross-domain-ajax-querying-with-jquery.html

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.

Categories

Resources