Json fetching has worked before in site for example here where i used the same processes - https://n-ce.github.io/Sea-arch
Here's the script
//FETCH
function content(a){
fetch(a+'.json').then(function (response) {
return response.json();
}).then(function (data) {
appendData(data);
}).catch(function (err) {
console.log('error: ' + err);
});
}
//Loading the objects
var root = document.getElementById('root');
function appendData(data) {
for (var i = 0; i < data.length; i++) {
var p = document.createElement("p");
p.innerHTML = data[i].Name;
root.appendChild(p);
}
}
// Remove Function
function remove(){
while (root.hasChildNodes()) {
root.removeChild(root.firstChild);
}
}
// Click decision making
var count = couns = 0;
function Sites() {
if(count%2==0){
content('Sites');
count++;
}
else{
count--;
remove();
}
}
function Animals() {
if (couns % 2 == 0) {
content('Animals');
couns++;
}
else {
couns--;
remove();
}
}
And this is the HTML
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON SD</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body onload="content('Onload')">
<span>
<button onclick="Animals()">Load Animals</button>
<button onclick="Sites()">Load Sites</button>
</span>
<div id="root"></div>
<script src="script.js"></script>
</body>
</html>
There is no way for me to debug this given that the console doesnot throw any errors since its working fine in localhost.
Im fairly new to the Fetch API But
Im thinking maybe it is because the json files are being transferred are taking too long?
Can someone please highlight whats the issue?
Here's how it worked for github pages, thanks to #programmarRaj for highlighting
Script
//FETCH
function content(a){
fetch("./"+a+".json").then(function (response) {
return response.json();
}).then(function (data) {
appendData(data);
}).catch(function (err) {
console.log('error: ' + err);
});
}
Related
I am trying to learn more about APIs and calling them correctly. I have been using the fetch method. My code, which includes the API I'm referencing:
fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
var div = document.createElement("div");
div.innerHTML = 'Name: ' + data[0].Population;
mainContainer.appendChild(div);
// }
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON Test</title>
</head>
<body>
<div id="myData"></div>
</body>
</html>
I'm trying to call upon "Population" for 2019 and display it. This is easy with a basic API with only one set of curly brackets and no arrays - but for this one I think I'm getting my arrays and objects mixed up and am not coding it in correctly, any suggestions?
This API returns an object with "data" property so you can use "data" property to display populations like this.
fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population')
.then(function (response) {
return response.json();
})
.then(function (data) {
const responseData = data.data;
appendData(responseData);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById('myData');
var div = document.createElement('div');
div.innerHTML = 'Name: ' + data[0].Population;
mainContainer.appendChild(div);
}
Working with trying to learn json and ajax and how they interoperate with html and javascript
I have a php with json data inside
I am trying to get the json data formatted into the html page but I keep getting error that "callback is not a function"
I am running the php and html files on my MAMP server to simulate a api feed
I will share my html and js files
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="run2.js"></script>
<title>Ajax Demo</title>
</head>
<body>
<h1 class="title">Todays Weather Forecast</h1>
<p class="sub">Click the button the check the local weather.</p>
<button class="demo-centered" type="button" onclick="loadPhp()">Check Weather</button><br><br>
<p id="demo"></p>
</body>
</html>
var loadPhp = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
loadPhp('demo.php', function (err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
for (var i = 0; i < data.length; i++) {
for (x in data[i]) {
console.log(data[i][x]);
}
}
}
});
PHP just in case
{"coord":{"lon":-116.8,"lat":33.03},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":293.73,"feels_like":289.89,"temp_min":289.26,"temp_max":295.93,"pressure":1016,"humidity":52},"visibility":16093,"wind":{"speed":5.7,"deg":260},"clouds":{"all":40},"dt":1589408840,"sys":{"type":1,"id":5686,"country":"US","sunrise":1589374130,"sunset":1589423903},"timezone":-25200,"id":5391832,"name":"San Diego County","cod":200}
You have to create a javascript function called callback to do what the you want the callback to do.
I have built a javascript code to be able to read any Youtube video transcript (gapi.client.youtube.captions.download). The auth 2.0 works fine, I run my app in a local web server everything is fine, the problem is that when I run the request I have the error 403: cb=gapi.loaded_0:164 GET https://content.googleapis.com/youtube/v3/captions/My_API_Key 403 I have not found any solution here in StackOverflow.. any idea ?
Here is my js file:
const CLIENT_ID = 'My_Client_ID';
const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"];
const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly';
const authorizeButton = document.getElementById('enter-button');
const signoutButton = document.getElementById('exit-button');
const content = document.getElementById('content');
// default youtube channel
const defaultChannel = 'googledevelopers';
// Load auth2 library
function handleClientLoad(){
gapi.load('client:auth2', initClient);
}
// Init API client library and set up sing in listeners
function initClient(){
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(() => {
// Listen for sing state changes
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle initial sign in state
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignouClick;
});
}
// update UI sign in state changes
function updateSigninStatus(isSignedIn){
if(isSignedIn){
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
content.style.display = 'block';
getChannel(defaultChannel);
}else{
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
content.style.display = 'none';
}
}
// Handle Login
function handleAuthClick(){
gapi.auth2.getAuthInstance().signIn();
}
// Handle Logout
function handleSignouClick(){
gapi.auth2.getAuthInstance().signOut();
}
// Display channel Data
function showChannelData(data){
const channelData = document.getElementById('channel-data');
channelData.innerHTML = data;
}
// Get channel from API
function getChannel(channel){
gapi.client.youtube.captions.download({
id: 'guMGyC1tUYAdL3hgBlcGnW4Rt_bBUbtp'
})
.then(response => {
console.log(response);
const channel = response.result.items[0];
})
.catch(err => alert('No Channel By THat Name'));
}
And here is my index.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your awesome Youtube search engine</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Awesome videos!" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<header>
<h1 class="w100 text-center">YouTube Viral Search</h1>
</header>
<div class="container">
<p>Login with Google</p>
<button class="btn green" id="enter-button">Log In</button>
<button class="btn green" id="exit-button">Log Out</button>
<br />
<div id="content">
<div class="row">
<div id="channel-data" class="col s12"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="/javascripts/appYT.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
enter code here
You can use the following code for get the transcript in a given video.
This is the working jsfiddle
N.B here I have the videoId zenMEj0cAC4, but you can change it as you desire.
$.ajax({
type: "GET",
url: "https://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
crossDomain: true,
}).done(function(data) {
console.log(data);
getCaption(data);
});
var parser, xmlDoc;
var HTML_captions = "";
// Parse the AJAX response and get the captions.
function getCaption(ajax_response) {
try {
parser = new DOMParser();
xmlDoc = parser.parseFromString(ajax_response, "text/xml");
//console.log(ajax_response);
//console.log(xmlDoc.getElementsByTagName("transcript").length);
if (xmlDoc.getElementsByTagName("transcript").length > 0) {
// Loop the results of the xmlDoc:
for (var i = 0; i < xmlDoc.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
} else {
// Loop the results of the ajax_response;
for (var i = 0; i < ajax_response.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
}
document.getElementById("demo").innerHTML = "<i>Preparing captions...</i>";
setTimeout(fillData(), 2000);
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at getCaption function - see console form more details.');
alert('Error at getCaption function - see console form more details.');
}
}
// Fill the data "captions" in a HTML "div" control.
function fillData() {
try {
document.getElementById("demo").innerHTML = HTML_captions;
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at fillData function - see console form more details.');
alert('Error at fillData function - see console form more details.');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="demo"><i>Loading captions...</i></div>
Just in case you need more information about how you can get automatic closed captions, you can refer to these answers in Stack Overflow:
Get closed caption “cc” for Youtube video
Extract automatic captions from YouTube video
This is my html file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Script-Type" content="text/javascript"/>
</head>
<body>
<label for=payload>Payload</label><br>
<textarea id="editor" cols=100 rows=30></textarea><br>
</body>
And the phantomjs script is:
var bodyParser = require('body-parser'),
phantom = require('phantom');
var bk = {"abc":"def"};
//Create Phantom session
var _phSession;
var _page;
var log = console.log;
var config = { logger: { warn:log, info:log, error:log } };
phantom.create([], config).then(function(_session) {
if (_session) {
console.log('Phantom session created');
_phSession = _session;
return _phSession.createPage();
}
})
.then(function(page) {
_page = page;
_page.property('onConsoleMessage', function(msg) {
console.log(msg);
});
_page.property('onLoadStarted', function() {
console.log("load started");
});
_page.property('onLoadFinished', function() {
console.log("load finished");
});
return _page.open("http://myserver/my.html");
})
.then(function(status) {
console.log('Open status:' + status);
if (status != 'success') return;
_page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js')
.then(function() {
//set the new bkstore
_page.evaluate(function(bk) {
jQuery('#editor').val(JSON.stringify(bk));
return jQuery('#editor').val();
}, bkstore)
.then(function(res) {
console.log('Return from set:' + res);
})
});
setTimeout(function() {
_page.evaluate(function() {
console.log('============== EVALUATE AFTER LOADED ===================');
//return jQuery('#editor').val();
return jQuery('body').html();
})
.then(function(res) {
console.log('html:' + res);
});
}, 1000);
After I set the #editor content with bk, I get back the value I set.
In the block of setTimeout, if I try to get the content of #editor again, I still get back the value of bk.
But I get the html of the body tag, I don't see the value of bk in the #editor.
Anyone knows what the problem is?
I am trying to display a particular webpage
https://www.emcsg.com/marketdata/priceinformation
but no matter what, my code only opens the home page of this website and not the link mentioned above. i tried the same code with many other websites, and it works fine. My code is as follows:
<html>
<head>
<title>NASA Meteorology </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script>
$(function(){
function requestCrossDomain(site, callback) {
if (!site) {
alert('No site was passed.');
return false;
}
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
window[callback](data);
} else throw new Error('Nothing returned from getJSON.');
}
}
$('#test').click(function(){
var url = 'https://www.emcsg.com/marketdata/priceinformation';
requestCrossDomain(url, 'someFunction');
});
});
function someFunction(results){
console.log(results);
$('#loadedContent').css("display","").html(results);
}
</script>
</head>
<body>
<button id="test">Submit</button>
<br><br>
<div id="result"></div>
<div id="loadedContent"></div>
</body>
</html>
where am i going wrong? Any suggestions or hel would be appreciated.. thanks
Change
&format=xml&callback=?
to
&format=json
And your $.getJSON will indeed get JSON
The result will be an object something like
{
"query": {
"count": 1,
"created": "2016-02-10T12:26:11Z",
"lang": "en-AU",
"results": {
"body": {
// removed for brevity
}
}
}
}
Try putting passing the params to ajax instead of attaching them to the url
var yql = 'http://query.yahooapis.com/v1/public/yql';
$.getJSON(yql,{q:'select * from html where url="' + site + '"',format:'json'},cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
window[callback](data);
} else throw new Error('Nothing returned from getJSON.');
}