When I try to return records from an Learning record store I am successful but it comes in as an unparsed array. Figure 1 below shows the code that is successful for me at bringing in this unparsed data.
When I use the code in Figure 2 to bring in just three parsed fields it doesn't work. After executing, nothing is displayed in the browser. Can someone help me with the code in Figure 2 ? Thanks very much.
Figure 1:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title>Get statements 101</title>
<script type="text/javascript" src="tincan.js"></script>
</head>
<body>
<h1>Pull info from the LRS</h1>
<div id='response'></div>
<script>
var tincan = new TinCan (
{
recordStores: [
{
endpoint: "https://lrs.adlnet.gov/xapi/",
username: "xapi-tools",
password: "xapi-tools",
allowFail: false
}
]
}
);
var container = document.getElementById('response');
tincan.getStatements({
'callback': function (err, result) {
container.innerHTML = (err !== null ? 'ERROR' : JSON.stringify(result.statements));
}
});
</script>
</body>
</html>
Figure 2:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title>Pulling Data from the LRS</title>
<script type="text/javascript" src="tincan.js"></script>
</head>
<body>
<h1>Get statements</h1>
<script>
var tincan = new TinCan (
{
recordStores: [
{
endpoint: "https://lrs.adlnet.gov/xapi/",
username: "xapi-tools",
password: "xapi-tools",
allowFail: false
}
]
}
);
tincan.getStatements({
'callback': function (err, result) {
container.innerHTML = (err !== null ? 'ERROR' : parseMyData(result));
}
});
parseMyData = function(result) {
var statements = result.statements;
var output = '';
var name,verb,activity;
for(var i=0;i<statements.length;i++){
// check the statement for a usable name value
// (priority = actor.name, actor.mbox, actor.account.name)
if(statements[i].actor.name != null && statements[i].actor.name != "") {
name = statements[i].actor.name
}else if(statements[i].actor.mbox != null && statements[i].actor.mbox != "") {
name = statements[i].actor.mbox
}else{
name = statements[i].actor.account.name
}
// check the statement for a usable verb value
// (priority = verb.display['en-US'], verb.id)
try{
verb = statements[i].verb.display['en-US'];
}catch(e){
verb = statements[i].verb.id;
}
// check the activity for a usable value
// (priority = definition.name['en-US'], id)
try{
activity = statements[i].target.definition.name['en-US'];
}catch(e){
activity = statements[i].target.id;
}
output += name + ' - ' +
verb + ' - ' +
activity +
'<br>'
}
return output;
</script>
</body>
</html>
Related
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);
});
}
//app.js
const SEARCH_VIEW = document.getElementById('search_view');
const RESULTS_VIEW = document.getElementById('results_view');
const FORECAST_VIEW = document.getElementById('forecast_view')
function loadCities(){
const cities = ["London", "Paris", "Madrid", "Lisbon","Ohrid"];
var options = null;
var dest = document.getElementById('dest');
//Looping the cities
cities.forEach(city => {
options += '<option>' + city +'</options>';
});
dest.innerHTML = options;
}
function gettingWeather(){
// 1. Open the Url
var dest = document.getElementById('dest').value;
var url = ('http://api.openweathermap.org/data/2.5/weather?q='+ dest + '&appid=exampleAppId');
console.log(url);
console.log(dest);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'visible';
// Temperature
document.getElementById('Temperature').textContent = data.main.temp;
//Wind
document.querySelector('.Wind').textContent = data.wind.speed * data.wind.deg;
//Description
document.querySelector('.Description').textContent = data.weather[0].description;
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
function forecast(){
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=exampleAppId&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest.value;
console.log(url);
console.log(dest.value);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'hidden';
FORECAST_VIEW.style.visibility= 'visible';
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width ,initial-scale=1">
<link href="styles.css" type="text/css" rel="stylesheet">
</head>
<body onload="loadCities();">
<div class="container">
<div id = "results_view">
<div class="inputWrapper">
<h1> Weather App </h1>
<p>Choose a city.</p>
<select id="dest" onchange="gettingWeather();" width=150 style="width:150px" ></select><br>
<label>Temperature</label>
<label class="Temperature" id="Temperature"></label><br>
<label>Wind</label>
<label class="Wind" id="Wind"></label><br>
<label>Description</label>
<h1 class="Description" id="Description"></h1>
<button onclick="forecast();">Forecast</button>
</div><!-- InputWrapper -->
</div>
<div id="forecast_view">
<h1>ForeCast</h1>
</div>
</div> <!-- end container -->
<script src="app.js"></script>
</body>
</html>
My task is to choose random 5 European cities and show some attributes but when a button is clicked I need to show a forecast of that city. I attempt to use Lexical Scoping to and half of my application works the easy part where i show some attribute taken from the API, when i clicked the button forecast I have error with the response Error but the error is also the city i choose.If I use any city the, in the forecast is undefined. I am not sure why I have this error and i dont have any insides tried closure If you don't know any answer I would appreciate even an insight or reference of work similar done.
Thank you
The problem is that your variable "dest" already contains the value. So you have in "dest" the name of your city and you use dest.value which is undefined because dest is a string and has no property called value.
to fix your code just remove .value in the url:
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=6c345b20d0c8fac21a36761eb7d6cd38&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest; // only dest NOT dest.value
console.log(dest); // the city selected
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 create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.
i recently found a script that uses cleverbot's api. i'm able to get a response when i enter a variable in the ask() function, but how can i make it so that a user can communicate with cleverbot by entering a value in an input box?
also, cleverbot's api only prints responses into the console.log() so i had to use the code at the bottom to transcribe the entries into the .console div:
$(document).ready(function() {
var bot = new cleverbot("BIsKhtIhZdmgbOPp", "DwikyXztHk6GEG7LcvHCKfObCxYduTMP");
bot.setNick("sessionname")
bot.create(function (err, session) {
// session is your session name, it will either be as you set it previously, or cleverbot.io will generate one for you
// Woo, you initialized cleverbot.io. Insert further code here
});
$('#clever').keyup(function (e) {
if (e.keyCode == 13) {
var value = $(this).val();
var input = value;
if (value == input) {
document.getElementById("input").innerHTML =
'<p>> ' + bot.ask(input, function (err, response) {
console.log(input);
console.log(response);
}); + '</p>';
}
}
});
if (typeof console != "undefined")
if (typeof console.log != 'undefined')
console.olog = console.log;
else
console.olog = function() {};
console.log = function(message) {
console.olog(message);
$('.console').append('<br>' + '<p>> ' + message + '</p>');
};
console.error = console.debug = console.info = console.log
});
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://unilogue.github.io/css/style.css">
<script type="text/javascript" src="https://unilogue.github.io/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://unilogue.github.io/js/cleverbot/cleverbot.io.js"></script>
</head>
<body>
<div class="console" style="width:75%;"></div>
<div id="input"></div>
<p>> </p><input id="clever" type="text" placeholder="say something clever." />
</body>
</html>
i updated the snippet and added an if... statement to enable dialogue.
$(document).ready(function() {
var bot = new cleverbot("BIsKhtIhZdmgbOPp", "DwikyXztHk6GEG7LcvHCKfObCxYduTMP");
bot.setNick("sessionname")
bot.create(function (err, session) {
// session is your session name, it will either be as you set it previously, or cleverbot.io will generate one for you
// Woo, you initialized cleverbot.io. Insert further code here
});
$('#clever').keyup(function (e) {
if (e.keyCode == 13) {
var value = $(this).val();
var input = value;
if (value == input) {
document.getElementById("input").innerHTML =
bot.ask(input, function (err, response) {
console.log('me > ' + input);
console.log('cb > ' + response); // Will likely be: "Living in a lonely world"
});
$(this).val('');
}
}
});
$('html').keydown(function(e) {
if (e.which == 118) {
window.open('/', '_self');
}
});
if (typeof console != "undefined")
if (typeof console.log != 'undefined')
console.olog = console.log;
else
console.olog = function() {};
console.log = function(message) {
console.olog(message);
$('.console').append('<br>' + '<p>' + message + '</p>');
};
console.error = console.debug = console.info = console.log
});
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://unilogue.github.io/css/style.css">
<script type="text/javascript" src="https://unilogue.github.io/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://unilogue.github.io/js/cleverbot/cleverbot.io.js"></script>
</head>
<body>
<div class="console"><div id="input" style="display:none;"></div></div>
<p>me > </p><input id="clever" type="text" placeholder="say something clever." spellcheck="false" />
</body>
</html>