My highstocks chart fetches JSON data from Yahoo and data from is structured like so "www.blahAAPLblah.com".
I want to change the value of AAPL in the URL to other company ticker symbols so that I can fetch the data and display it on my chart. If I change the string manually to GOOG then it will work fine. Also if I put var ticker = 'GOOG' and change the URL to "www.blah" + ticker + "blah.com" then this also works fine.
If I have a user input box and have var ticker = document.getElementById('userInput').value; then everything stops working.
Do you have any suggestions at all?
Here is my code so far: http://jsfiddle.net/SgvQu/
UPDATE I have attempted to use JSONP to perform the request but the chart is still not loading.
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
Thanks to Sebastian Bochan for pointing me in the right direction with JSONP. I now have the chart functioning correctly :)
Related
I am trying to convert a JSON string into an integer so that I can use this data in a google chart. As of right now I can only get one set of data to be displayed in my chart.
Here is my JQUERY code:
$("#shotsandbigcc").click(function(){
//alert("Button works");
$("#shotsandbigcc_popup").toggle();
var integer = $("#shotsandbigcc").attr("name");
//alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {myData: integer},// data to submit
dataType: 'json',
success: function(response){
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMultSeries);
function drawMultSeries() {
var len = response.length;
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable([
['Year', 'Shots on Target', 'Shots off Target'],
[year, ontarget, offtarget],
[year, ontarget, offtarget]
]);
var options = {
title: 'Shooting Accuracy',
chartArea: {width: '50%'},
hAxis: {
title: 'Amount of Shots',
minValue: 0
},
vAxis: {
title: 'Year'
}
};
var chart = new google.visualization.BarChart(document.getElementById('shotsandbigcc_chart'));
chart.draw(data, options);
}
}
});
});
The JSON data is in an array which has this format [{"Year":"2019/2020","Shots_on_Target":"302","Shots_off_Target":"578","Accuracy":"0.34"},{"Year":"2020/2021","Shots_on_Target":"74","Shots_off_Target":"93","Accuracy":"0.44"}]
If someone could tell me how I can display both 2019/2020 and 2020/2021 data to be displayed. I would be most grateful as right now only the 2020/2021 data is being displayed. Thank you.
For integet value part:
var ontarget = parseInt(response[i].Shots_on_Target);
For your data part:
var vizData = [];
vizData.push(['Year', 'Shots on Target', 'Shots off Target']);
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
vizData.push([year, ontarget, offtarget]);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable(vizData);
explaination: since in the loop the values are getting updated in every iteration so, the 'year', 'ontarget' and 'offtarget' will have the latest values only. So on every iteration you have to store values so that they do not get overwritten. For that now this code is pushing in array in every iteration preserving the previous values. Which now you can use in the google.visualization function.
Happy Coding!
I need to create a table from JSON, I'm getting output in a string and it should be printed in table format in HTML
function apicall(){
var id = document.getElementById('idval').value;
var url1 = '**********************';
var token = sessionStorage.getItem('MyUniqueUserToken');
var data1 = {"ip":id};
var success = {};
var dataType = {};
$.ajax({
url: url1,
data: data1,
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'token '+token);},
success: function(res) {
document.getElementById('output').innerHTML =JSON.stringify(res[0]);
}
});
}
enter image description here
Guessing that res is the response as a JSON so instead of
document.getElementById('output').innerHTML =JSON.stringify(res[0]);
you have to put your response into a loop (Given you have an empty table with cells=fields output0 to output4
var i=0;
response.data.forEach(function(field) {
//here you create the table cells if there are 5 fields
that would be 5 cells as I do not know the structure just
pseudo code
document.getElementById('output'+i).innerHTML = JSON.stringify(res[i]);
i = i+1;
}
if you want to semi dynamicly create table rows you have to have a table with header (footer) row fix and the tabelbody as an anchor to whichyou append the created rows could look like follows (partly pseudo code) -PLAIN vanilla javascript as I do not like jquery:
// We need a table definition for creating headers and interpreting JSON date
var tdataRow = [{
"output0" : field.output0,
"output1" : field.output1,
"output2" : field.output2,
"output3" : field.output3;
"output4" : field.output4
}];
// Then in jour ajax
response.data.forEach(function(field) {
var columnHeadings = Object.keys(tdataRow[0]);
var tableRef = document.getElementById("tbody" + "my_test_table");
var columnCount = 5; // Could be derived from number of headings
var tableLength = tableRef.getElementsByTagName("tr").length;// we get the number of the existing table rows
var trowID = tableLength + 1; // we append at the end of existing rows
var tableRow = tableRef.insertRow(tindex);
for (var j = 0; j < columnCount; j++) { /* Each column */
var cell = tableRow.insertCell(-1);
cell.setAttribute("id", columnHeadings[j] );
var obj = tdataRow[0];
cell.innerText = obj[columnHeadings[j]]; // we get the field names from the header
}
tableRow.setAttribute("id", "row" + "my_test_table" + j );
// examples how to style and use classes
tableRow.classList.add("table");
tableRow.classList.add("clickable-row");
tableRow.setAttribute("align","center");
// if you want to catch clicks on the row
tableRow.addEventListener("click", function(){
// do something with the row e.g. highlight/ get values etc
}
}
The second solution can be converted into a fully automated/dynamic solution where everything is created from the JSON - but small steps first.
I use the code below to retrieve a XML and write the data to Sheet2.
But when i run the function again it loads the entire xml again into the sheet.
What i want to achieve, but don't know how:
1.
Get de XML and compare it with the data already in Sheet2, based on 2 colums:
stationID & stationTypeID
2.
When the two columns match, update the entire row. When the columns don't match, insert the new row on top.
function loadOutposts(){
var outposts= new Array();
var url = "https://api.eveonline.com/eve/ConquerableStationList.xml.aspx";
var parameters = {method : "get", payload : ""};
var xmlFeed = UrlFetchApp.fetch(url, parameters).getContentText();
var xml = XmlService.parse(xmlFeed);
if(xml) {
var rows=xml.getRootElement().getChild("result").getChild("rowset").getChildren("row");
for(var i = 0; i < rows.length; i++) {
outpost=[rows[i].getAttribute("stationID").getValue(),
rows[i].getAttribute("stationName").getValue(),
rows[i].getAttribute("stationTypeID").getValue(),
rows[i].getAttribute("solarSystemID").getValue(),
rows[i].getAttribute("corporationID").getValue(),
rows[i].getAttribute("corporationName").getValue()
]
outposts.push(outpost);
}
}
//return outposts;
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2').getRange(1,1,outposts.length,outposts[0].length).setValues(outposts);
};
Thx for the help!
How about this modification?
Flow :
Data retrieved by UrlFetchApp.fetch() is compared to the existing data on Spreadsheet.
When the columns 1 and 2 for them are same, the existing data is updated.
When the data retrieved from URL is not included in the existing data, the data is inserted to the top of existing data. This existing data becomes new data.
Then, the data on Spreadsheet is updated by new data.
Modified script :
function loadOutposts(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2');
var outposts= new Array();
var url = "https://api.eveonline.com/eve/ConquerableStationList.xml.aspx";
var parameters = {method : "get", payload : ""};
var xmlFeed = UrlFetchApp.fetch(url, parameters).getContentText();
var xml = XmlService.parse(xmlFeed);
if (xml) {
var rows=xml.getRootElement().getChild("result").getChild("rowset").getChildren("row");
for(var i = 0; i < rows.length; i++) {
outpost = [
rows[i].getAttribute("stationID").getValue(),
rows[i].getAttribute("stationName").getValue(),
rows[i].getAttribute("stationTypeID").getValue(),
rows[i].getAttribute("solarSystemID").getValue(),
rows[i].getAttribute("corporationID").getValue(),
rows[i].getAttribute("corporationName").getValue()
]
outposts.push(outpost);
}
// ----- Added script
if (ss.getLastRow() > 0) {
var currentdata = ss.getRange(2, 1, ss.getLastRow(), ss.getLastColumn()).getValues(); // Updated
currentdata.forEach(function(e1, i1){
var temp = [];
outposts.forEach(function(e2, i2){
if (e1[0] == e2[0] && e1[1] == e2[1]) {
currentdata[i1] = e2;
temp.push(i2);
}
});
for (var i in temp) {
outposts.splice(temp[i], 1);
}
});
Array.prototype.push.apply(outposts, currentdata);
}
// -----
}
ss.getRange(2,1,outposts.length,outposts[0].length).setValues(outposts); // Updated
};
If I misunderstand your question, I'm sorry.
I am trying to run my script that is going to search for a movie title from a movie database. I get results in the console and no errors. But in my renderMovies function it's supposed to store the API movie title, plot etc in my variables, but when I print it out in a list it either gives me nothing (blank) or undefined. I am kind of new to jQuery, AJAX and APIs so I'm following a guide, so the code is not entirely written by me.
OBS: I get undefined when using this $("<td>" + plot + "</td>"), but blank when using $("<td>").append(title). You can find that code in the middle of the renderMovies function.
For example: I search for the movie 'Avatar' and I get two results. However the two results gets "stored" as undefined in the plot description and blank from the title.
$(document).ready(function(){
$(init);
function init() {
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody");
function searchMovie(){
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0"es=0&fullSize=0&companyCredits=0&filmingLocations=0",
dataType: "jsonp",
success: renderMovies
});
};
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I've reordered your functions and calls because some of the variables were undefined. (Google Chrome -> F12 (opens developers console))
This returns a response on a button click.
$(document).ready(function () {
function searchMovie() {
var movieTitle = $("#movieTitle");
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0"es=0&fullSize=0&companyCredits=0&filmingLocations=0",
dataType: "jsonp",
success: renderMovies
});
}
function renderMovies(movies) {
console.log(movies);
var movieInfo = movies.data.movies;
var table = $("#results");
var tbody = $("#results tbody");
tbody.empty();
for (var m in movieInfo) // Tar information från apin och stoppar in i egna variabler.
{
var movie = movieInfo[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
$("#searchMovie").click(searchMovie);
});
I have a mobile app in HTML5 that is using the websql database. I have a data.js file with a bunch of functions for doing various CRUD jobs with the database. I've never had this problem until I got to wiring this function. Basically the app is for creating quotes for tradesmen and the function I'm writing is getting the quote and quote lines, converting them into and array of JSON objects and ajaxing them to a web app.
For some reason my db.transaction's are not being executed. Can you help me figure out why? The db exists as other functions are calling this exact SQL. But it works for them and not this one:
function syncQuote(){
var quote_id = localStorage["quote_id"];
var header = new Array(); // holds id, created, appointment_id
db = openDatabase("Quote", "0.1", "A collection of quotes.", 200000);
if(!db){
console.log('Failed to connect to database.');
}
console.log('Getting quote header data.');
db.transaction(
function(tx) {
tx.executeSql("SELECT * FROM quote_header WHERE id = ?", [quote_id],
function(tx, results) {
var len = results.rows.length;
for(var i=0; i< len; i++){
alert('booyah!');
header['quote_id'] = results.rows.item(i).id;
header['appointment_id'] = results.rows.item(i).appointment_id;
header['created'] = results.rows.item(i).created;
}
});
},
function(tx, error){
console.log(error.message);
}
);
// now get all quote lines for this quote
var lines = new Array();
console.log('getting quote lines');
db.transaction(
function(tx) {
tx.executeSql("SELECT DISTINCT areas.label as area, features.label as feature, products.label as product, hours, price, colour FROM quote_line JOIN areas ON quote_line.area_id = areas.area_id JOIN features ON quote_line.feature_id = features.feature_id JOIN products ON quote_line.product_id = products.product_id WHERE quote_line.quote_id = ?", [quote_id],
function(tx, results) {
len = results.rows.length;
for(var i=0; i< len; i++){
var area= results.rows.item(i).area;
var feature= results.rows.item(i).feature;
var product= results.rows.item(i).product;
var hours= results.rows.item(i).hours;
var price= results.rows.item(i).price;
var colour= results.rows.item(i).colour;
lines[i] = new Array(6);
lines[i][0] = area;
lines[i][1] = feature;
lines[i][2] = product;
lines[i][3] = hours;
lines[i][4] = price;
lines[i][5] = colour;
}
},
function(tx, error){
console.log(error.message);
}
);
}
);
var data = new Array(2);
data[0] = JSON.stringify(header);
data[1] = JSON.stringify(lines);
alert(data[0]);
alert(data[1]);
// post data to web app
var url = "http://*****.com/import_quote";
$.ajax({
type: 'POST',
url: url,
data: data,
success: quote_sync_success,
dataType: 'JSON'
});
}
I have both success and fail callbacks but neither is responding.
Also this is the first time I'm posting JSON from a JS app so feel free to comment.
Thanks,
Billy
Copy this edited codes and see if it works
function syncQuote(){
var quote_id = localStorage["quote_id"];
var header = new Array(); // holds id, created, appointment_id
db = openDatabase("Quote", "0.1", "A collection of quotes.", 200000);
if(!db){
console.log('Failed to connect to database.');
}
console.log('Getting quote header data.');
db.transaction(
function(tx) {
// CORRECTION 1: THE ? IS MEANT TO BE IN A BRACKET
tx.executeSql("SELECT * FROM quote_header WHERE id = (?)", [quote_id],
function(tx, results) {
var len = results.rows.length;
for(var i=0; i< len; i++){
alert('booyah!');
header['quote_id'] = results.rows.item(i).id;
header['appointment_id'] = results.rows.item(i).appointment_id;
header['created'] = results.rows.item(i).created;
}
});
},
function(tx, error){
console.log(error.message);
},
//CORRECTION 2
//THERE IS MEANT TO BE A SUCCESS CALL BACK FUNCTION HERE
function(){
console.log( 'Query Completed' )
}
);
// now get all quote lines for this quote
var lines = new Array();
console.log('getting quote lines');
db.transaction(
function(tx) {
// CORRECTION 3: WRONG CALL METHOD AND NONE-USE OF BRACKETS and QOUTES
tx.executeSql("SELECT DISTINCT areas.label as area, features.label as feature, products.label as product, hours, price, colour FROM quote_line JOIN areas ON quote_line.area_id = 'areas.area_id' JOIN features ON quote_line.feature_id = 'features.feature_id' JOIN products ON quote_line.product_id = 'products.product_id' WHERE quote_line.quote_id = (?)", [quote_id],
function(tx, results) {
len = results.rows.length;
for(var i=0; i< len; i++){
var area= results.rows.item(i).area;
var feature= results.rows.item(i).feature;
var product= results.rows.item(i).product;
var hours= results.rows.item(i).hours;
var price= results.rows.item(i).price;
var colour= results.rows.item(i).colour;
lines[i] = new Array(6);
lines[i][0] = area;
lines[i][1] = feature;
lines[i][2] = product;
lines[i][3] = hours;
lines[i][4] = price;
lines[i][5] = colour;
}
},
function(tx, error){
console.log(error.message);
}
);
}
);
var data = new Array(2);
data[0] = JSON.stringify(header);
data[1] = JSON.stringify(lines);
alert(data[0]);
alert(data[1]);
// post data to web app
var url = "http://*****.com/import_quote";
$.ajax({
type: 'POST',
url: url,
data: data,
success: quote_sync_success,
dataType: 'JSON'
});
}
have you tried throwing console.log()'s in at the start of your success callbacks? if len is 0 in those, you wouldn't get any output from them as is