How can I get javascript to read from a .json file? - javascript
My script currently looks like this:
<script type="text/javascript">
function updateMe(){
var x = 0;
var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
var activity=JSON.parse(jsonstr);
while(x<10){
date = document.getElementById("date"+x).innerHTML = activity.date;
event = document.getElementById("event"+x).innerHTML = activity.event;
x++;
}
}
</script>
Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.
The local .json file looks like this:
{"date":"July 4th", "event":"Independence Day"}
Any suggestions?
Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA
If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<p>Take a look at json_demo.txt</p>
</body>
</html>
It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Here's a summary:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Here's the example used:
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:
Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.
If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/
Since it isn't working, I'd try using XMLHttpRequests
You could also try AJAX requests:
$.ajax({
'async': false,
'global': false,
'url': "/jsonfile.json",
'dataType': "json",
'success': function (data) {
// do stuff with data
}
});
Documentation: http://api.jquery.com/jquery.ajax/
You can do it like...
Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.
$.ajax({
url: "File.json", //the path of the file is replaced by File.json
dataType: "json",
success: function (response) {
console.log(response); //it will return the json array
}
});
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal;
E.g.
window.portalData = [
{
"kpi" : "NDAR",
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]
},
{
"kpi" : "NTI",
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]
},
{
"kpi" : "BS",
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]
},
{
"kpi" : "SISS",
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]
},
{
"kpi" : "MID",
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]
}
];
You can then do the following in your HTML
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');
Related
use a .gs file in a web page in App Script
I'm using a script to extract data from google search console in a sheet. I built a sidebar to chose on which website the user want to analyse his data. For that i have a function that can list all sites link to the google account, but i have an error when i try to execute this function in my html file. I use withSuccessHandler(function) method which sets a callback function to run if the server-side function returns successfully. (i have a OAuth2.0.gs file where is my getService function. The error is "service.hasAccess is not a function at listAccountSites" where listAccountSites is my function. Here's an extract of my html file: <script src="OAuth2.0.gs"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script> <script> $(function() { var liste = google.script.run.withSuccessHandler(listAccountSites) .getService(); console.log(liste); }); function listAccountSites(service){ if (service.hasAccess()) { var apiURL = "https://www.googleapis.com/webmasters/v3/sites"; var headers = { "Authorization": "Bearer " + getService().getAccessToken() }; var options = { "headers": headers, "method" : "GET", "muteHttpExceptions": true }; var response = UrlFetchApp.fetch(apiURL, options); var json = JSON.parse(response.getContentText()); Logger.log(json) console.log('if') var URLs = [] for (var i in json.siteEntry) { URLs.push([json.siteEntry[i].siteUrl, json.siteEntry[i].permissionLevel]); } /* newdoc.getRange(1,1).setValue('Sites'); newdoc.getRange(1,3).setValue('URL du site à analyser'); newdoc.getRange(2,1,URLs.length,1).setValues(URLs); */ console.log(URLs); } else { console.log('else') var authorizationUrl = service.getAuthorizationUrl(); Logger.log('Open the following URL and re-run the script: %s', authorizationUrl); Browser.msgBox('Open the following URL and re-run the script: ' + authorizationUrl); } return URLs; } </script>
i found the solution. Jquery is useless here, you just have to use google.script.run.yourfunction() to run your gs. function on your html sidebar.
SoundCloud API gives "Uncaught SyntaxError: Unexpected token : " error
In the console it's giving me the error "Uncaught SyntaxError: Unexpected token : ", but if I access direct SoundCloud URL in my browser then it's giving valid JSON. Earlier this code was working fine and today this issue started. <html> <head> <script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script> </head> <body> <h2>hellooo</h2> </body> </html> Update: Below is the actual code for which I am asking the question, above html I just created for example. SoundCloud.prototype._jsonp = function (url, callback) { var target = document.getElementsByTagName('script')[0] || document.head; var script = document.createElement('script'); var id = 'jsonp_callback_' + Math.round(100000 * Math.random()); window[id] = function (data) { if (script.parentNode) { script.parentNode.removeChild(script); } window[id] = function () {}; callback(data); }; script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + id; target.parentNode.insertBefore(script, target); };
I got the reason of issue, earlier soundcloud were responding response in jsonp but now they are providing JSON even I passed JsonP callback function. I had to make ajax request to fix it. I used following code to fix it. var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { callback( JSON.parse(this.responseText) ); } }; xhttp.open("GET", url, true); xhttp.send();
The following script tag expects JavaScript code in the source and not JSON. <script src="file.js"></script>
I suppose that you want to use this externally produced json... A way to "get" it is using an asynchronous ajax request like $.get(url,callback); Calling it as a script will sure fail... Because it's not a script. Try to run the snippet! var url = "https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5" var json; $.get(url,function(result){ json = result; // show in console console.log(JSON.stringify(json)); // Now using it... $("#json_usage").html(json.tag_list+" and all the "+json.permalink); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <!--script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script--> </head> <body> <h2>hellooo <span id="json_usage"></span> !</h2> </body> </html> In the above, the resulting json is placed in the json variable and then console logged.
Sorry you've been having trouble with JSONP responses from the SoundCloud API. This was due to a bug that made it into production in the last few days. We've just deployed a fix, and so this endpoint will now be returning valid JSONP responses rather than just JSON, if you specify a callback parameter. Sorry for the confusion!
How do I fetch PHP script output from Javascript?
This is an example of the PHP script I want to get the output from within my javascript file: data.php <?php $input = file_get_contents('data.txt'); echo $input."\n"; ?> script.js $(document).ready(function(){ var data; // get output from data.php console.log( data ); }); I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page. I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time. I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code. script.js.php <?php header('Content-Type: application/javascript'); ?>console.log("<?php $input = file_get_contents('data.txt'); echo $input."\n"; ?>"); $(document).ready(function(){ $("#imgTag, #img2").on("click", process); var size = 0; function getTarget(evt) { evt = evt || window.event; return evt.target || evt.scrElement; } var temp; console.log("before get"); console.log("post get"); console.log(size); function changeSize(myName, myOther) { var name = myName; var other = myOther; if($("#" + name).height() < 400) { $("#" + name).height($("#" + name).height() + 5); $("#" + name).width($("#" + name).width() + 5); $("#" + other).height($("#" + other).height() - 5); $("#" + other).width($("#" + other).width() - 5); } } function process(event) { var name = getTarget(event).id; var other; if(name == "imgTag") { other = "img2"; } else other = "imgTag"; console.log($("#" + name)); console.log("Changing size!!!"); console.log( $("#" + name).height()); changeSize(name, other); } });
You can read that text file directly with jquery like this: $.ajax({ url : "data.txt", dataType: "text", success : function (data) { // Display the data in console console.log(data); // Or append it to body $('body').append(data); } }); The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc. Documentation: https://api.jquery.com/jQuery.ajax/
Parsing XML JQuery Ajax Response with Namespace
I'm executing a web service call using JQuery and it's ajax function and I'm unable to parse the data coming back. When I alert the data (alert($(data).find("return").text()) its empty. I see the server responding with xml data as outlined below and when I alert(data) I get [object XMLDocument]. Is txt = $(data).find("return").text() valid given my XML structure with a namespace below? I can see the full xml string in firebug. Any ideas? var txt = $(data).find("ns1\:return").text(); works on Chrome and Firefox, but not Safari index.js: $(function () { $.ajax({ url: url, success: function (data) { var ndx = 0, row, **txt = $(data).find("return").text(),** xml = unescape(txt), xmlDoc = $.parseXML(xml), firstrow = $(xmlDoc).find( "results").children(":first"); // populate the table based on the results returned by // the web service $("table.results thead").empty(); $("table.results tbody").empty(); row = $("<tr/>"); row.append($("<th/>").text("#").addClass("ndx")); firstrow.children().each(function () { row.append($("<th/>").text(this.nodeName)); }); row.appendTo($("table.results thead")); $(xmlDoc).find("row").each(function () { row = $("<tr/>"); row.append($("<td/>").text(ndx + 1).addClass("ndx")); $(this).children().each(function () { row.append($("<td/>").text($(this).text())); }); row.appendTo($("table.results tbody")); ndx++; }); // clear the table if no results were returned if (ndx == 0) { // no rows returned $("table.results thead").empty(); $("table.results tbody").empty(); } statusNotice("Records Returned: " + ndx); }, error: function(XMLHttpRequest, textStatus, errorThrown) { // display the error returned by the web service var xmlDoc = $(XMLHttpRequest.responseXML); statusError(xmlDoc.find("Text").text()); }, complete: function(XMLHttpRequest, textStatus) { // hide the busy dialog $("#busy-dlg").dialog("close"); } }); }); index.html: Demo <script type="text/javascript" src="js/jquery-1.6.4.min.js"></script> <script type="text/javascript" src="js/jquery-ui-min.js"></script> <script type="text/javascript" src="js/jquery.layout-latest.js"></script> <script type="text/javascript" src="js/index.js"></script> </head> <body> //table displaying results from ajax call here </body> </html> XML: <ns1:executeResponse xmlns:ns1="http://sqlws.test.com"> <ns1:return> <results> <row> <attribute1>value1</attribute1> <attribute2>value2</attribute2> </row> <row> <attribute1>value1</attribute1> <attribute2>value2</attribute2> </row> </results> </ns1:return> </ns1:executeResponse>
When an element is prefixed by a namespace, you have to also add the namespace: .find('ns1:return') does not work, because : is used by jQuery as pseudo-selectors. .find('ns1\:return') does not work either, because a single backslash in a string is used as an escape character. "ns1\:return" becomes "ns1:return" which is equal to the previous one. .find('ns1\\:return') should be used. The double backslash is used to escape the colon. It appears that the last solution works fine in IE and Firefox, but not Opera, Chrome or Safari. To get maximum compatibility, use jQuery selectors with, and without fake prefix, ie. "ns1\\:return, return" instead of a plain ns1\\:return. Demo: http://jsfiddle.net/5BQjv/51/ // For example, this is the result: var data = '<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">' + '<ns1:return>' + '<results> <row> ... </row> </results>' + '</ns1:return>' + '</ns1:executeResponse>'; // The very first thing is to parse the string as XML. NOT later! var $xmlDoc = $($.parseXML(data)); // Then, look for the element with the namespace: var $txt = $xmlDoc.find('ns1\\:return, return'); // No need to use unescape or something, just use DOM manipulation: // `results` is the immediate child. Don't use .find, but .children var $firstrow = $txt.children("results").children(":first"); As you may have noticed, I have prefixed some variables with a dollar sign. It's the convention to prefix variables which refer to jQuery objects with a dollar sign, to avoid confusion during/after development.
Populating A Page with XML and Javascript/Jquery, checking if the url is the same as an xml tag
I need to create a javascript function that will write a page based on the url, so basically I am trying to create a javascript function that will check the url, and find the corresponding xml item from there. The reason behind this is so that the html page can just be duplicated, renamed, and the xml updated, and the page will fill in everything else from the xml sheet. please let me know whether this is the completely incorrect way to do it, of it there is a better way. thanks!!! XML CODE:: <!--XML INFORMATION--> <channel> <design> <motion><!--design content--> <item><!--//////////POST//////////POST//////////POST//////////--> <tag>/portfolio_dec.html</tag> <!--RSS INFORMATION--> <title>Decoze</title> <link>http://payamrajabi.com/portfoliotest.html</link> <description><img src="http://payamrajabi.com/thumbs/small_jump.png" title="JUMP!." /></description> <!--PROJECT CONTENT--> <project><!--project start--> <titl>TITLE</titl><!--project title--> <dsc>PROJECT DESCRIPTION</dsc><!--project description--> </project><!--project end--> </item><!--//////////END//////////END//////////END//////////--> </motion> </design> </channel> JAVASCRIPT: $(document).ready(function(){ $.ajax({ type: "GET", url: "code/content9.xml", dataType: "xml", success: function(xml) { var xpathname = window.location.pathname; var xproject = $(xml).find('tag').text(); if (xpathname == xproject) { $(xml).find('item').children('tag').text(xpathname).each(function(){ var ttl = $(this).find('titl').text(); $('<p>'+ttl+'</p>').appendTo('h1#ttl'); }); $(xml).find('item').children('tag').text(xpathname).each(function(){ var dsc = $(this).find('dsc').text(); $('<p>'+dsc+'</p>').appendTo('h1#ttl'); }); } else { PUT ERROR MESSAGE HERE } } }); }); and THE HTML: <html> <head> <script type="text/javascript" src="code/jquery-1.3.1.js"></script> <script type="text/javascript" src="code/project/project_design.js"></script> </head> <body> <h1 id="ttl"></h1> <p id="dsc"></p> </body> </html> any help would really be appreciated, i am frairly new to javascript/jquery/xml, and am really having trouble with this. The primary thing I want to do is have an xml file that populates a site, with each item being the content for a new page, in this case of a portfolio item. cheers! willem
Hmm... I'm afraid you don't quite understand how jquery works. Your code should look something like this: var xpathname = window.location.pathname; var xitem = $(xml).find('tag:contains(' + xpathname + ')').parent(); if (xproject.length != 0) { $('#ttl').append('<p>' + xitem.find('titl').text() + '</p>'); $('#dsc').append('<p>' + xitem.find('dsc').text() + '</p>'); } else { $('#err').text('The page you requested does not exist'); } Demo 1 Here's a quick demo. Take a look at the source to see the XML and the JavaScript. http://jsbin.com/ujiho#itemOne http://jsbin.com/ujiho#itemTwo http://jsbin.com/ujiho#itemThree Demo 2 I've created another demo that uses $.get to retrieve the XML from a separate URL. http://jsbin.com/aqefo#nov http://jsbin.com/aqefo#dec The XML: http://jsbin.com/afiwa Here's the JavaScript. Let me know if you need help understanding anything. $(function(){ $.get( 'http://jsbin.com/afiwa', function(xml){ var hash = window.location.hash.substring(1); if ($.trim(hash) === '') { showError(); return; } var xitem = $(xml).find('urlname:contains(' + hash + ')').parent(); if (xitem.length != 0) { $('#ttl').append(xitem.find('titl').text()); $('#dsc').append( xitem.find('dsc').text()); } else { showError(); } function showError() { $('#err').text('The page you requested does not exist'); } } ); });