I have the following data in a JSON file (pio2.json)
{
"controles":[{
"chart":[{
"type":"columns",
"title":"Pollitos"
}],
"datos":[{"key":"Math","value":98},
{"key":"Physics","value":78},
{"key":"Biology","value":70},
{"key":"Chemistry","value":90},
{"key":"Literature","value":79}
]
}]
}
I need to extract data in array for a chart from "datos" for my html / javascript
$(function () {
var processed_json = new Array();
$.getJSON('pio2.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
}
}
Any advice?
not sure what your issue is. I should be serialized server side and deserialized client side. When deserialized, it will be in an array.
I copied your data, as is, into json1.json pasted in your code and made some minor changes and it worked fine. I got the results out of the json page into my html page.
<body>
<script type="text/javascript">
$(document).ready(function () {
var processed_json = new Array();
$.getJSON('json1.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
})
});
</script>
</body>
Related
I use Javascript. I want to get RSS data by API google (this link: http://www.javascriptkit.com/dhtmltutors/googleajaxfeed.shtml ), then insert the data into a Array (Global variable). But my global variable can not save data.
Inside rssfeedsetup() function, ARR_DATA (Global Array) have data. However, after load rssfeedsetup() function, ARR_DATA have no data.
Please show me, how to insert data to global variable in this case.
My code:
Head:
<head>
<title>TEST API FEED RSS</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
</script>
</head>
Body:
<body>
<div id="feeddiv"></div>
<script type="text/javascript">
var ARR_DATA = []; // **I want to insert data into this array**
var feedurl = "http://rss.slashdot.org/Slashdot/slashdot";
var feedlimit = 4;
function rssfeedsetup() {
var feedpointer = new google.feeds.Feed(feedurl); //Google Feed API method
feedpointer.setNumEntries(feedlimit); //Google Feed API method
feedpointer.load(displayfeed); //Google Feed API method
}
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
var arr_Temporary = [];
for (var i = 0; i < thefeeds.length; i++) {
arr_Temporary[0] = thefeeds[i].title;
arr_Temporary[1] = thefeeds[i].link;
// insert RSS data into ARR_DATA.
ARR_DATA.push(arr_Temporary);
console.log('value before:', ARR_DATA); // check value of ARR_DATA, there have data exist.
}
}
}
window.onload = function () {
rssfeedsetup(); // call function
console.log('value2 after:', ARR_DATA); // check value of ARR_DATA, there is no data.
};
console.log('value2 after:', ARR_DATA); //check value of ARR_DATA, there is no data.
</script>
</body>
I have got value console:
image of firebug on firefox
Ps: Why ARR_DATA no contain data after load function rssfeedsetup()?
You can push data into the array like this:
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
for (var i = 0; i < thefeeds.length; i++) {
var feed = {
title: thefeeds[i].title,
link: thefeeds[i].link
};
ARR_DATA.push(feed);
}
console.log(feed);
}
}
Hope it helps
I want to return a datatable I created in google apps script with data from a Spreadsheet to the client. I use a succesHandler to get the data and use this to create a chart. The only problem i have is that my data is null. It seems i can't return a datatable object to the client page.
I need to send it to the client, because Google Apps script is deprecating the UIApp functions so i need the google.visualization functions in the Client.
Code.gs
function doGet() { return HtmlService.createHtmlOutputFromFile('Index.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);}
function getDataTable()
{
var bestanden = DriveApp.searchFiles('title contains "' + "kwalrap" + '"');
while (bestanden.hasNext())
{
var bestand = bestanden.next();
var docid = ( bestand.getId() );
Logger.log(docid);
};
var sheets= SpreadsheetApp.openById(docid).getSheets();
//vanaf sheet 0. tot hij bij de laatset sheet is. dan steeds 2 sheets verder.
for(var j = 0; j < 2; j = j+1)
{
var sheet = sheets[j];
//Logger.log(sheet.getSheetName());
var range = sheet.getRange(2,1,sheet.getLastRow(),8);
var inforange = sheet.getRange(2,1,1,8);
var values = range.getValues();
var infovalues = inforange.getValues();
var data = Charts.newDataTable()
.addColumn(Charts.ColumnType.STRING, "Tijd")
.addColumn(Charts.ColumnType.NUMBER, "dco")
.addColumn(Charts.ColumnType.NUMBER, "dcp")
.addColumn(Charts.ColumnType.NUMBER, "dct")
.addColumn(Charts.ColumnType.NUMBER, "dcz")
.addColumn(Charts.ColumnType.NUMBER, "ldc")
.addColumn(Charts.ColumnType.NUMBER, "lv")
for(var i = 0; i < sheet.getLastRow()-1; i++)
{
data.addRow([values[i][0],values[i][1],values[i][2],values[i][3],values[i][4],values[i][5],values[i][6]]);
Logger.log(values[i]);
}
var dataTable = data.build();
return dataTable;
// return JSON.stringify(values);
}
}
Index.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function onSuccess(data) {
var options = {
title: 'Why doesn't this work'
};
new google.visualization.LineChart(
document.getElementById('visualization_div')).draw(data, options);
}
google.script.run.withSuccessHandler(onSuccess)
.getDataTable();
</script>
</head>
<body>
<div id="visualization_div" style="width: 600px; height: 380px;';"></div>
</body>
</html>
why is my data variable null in the onSuccesHandler and how do i get the datatable in the client
Thanks for your help
Its because you need to return a plain javascript array, not a data table which is purely a server-side object.
I'm pulling data from Google Calendar events and wanting to display it in my HTML markup. I've got the data being pulled successfully from Google and thought I was passing it into and array the proper way and encoding into JSON. I was also able to make the GET request via JQuery and confirmed it by checking the console to see if it was received. The problem was trying to display it in the HTML markup.
But, after further debugging, it seems my JSON array isn't correct. Almost as if it duplicates itself everytime it looks for more data from Google.
Here is my code:
<?php
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
include('google-api-php-client-master/autoload.php');
date_default_timezone_set('America/New_York');
//TELL GOOGLE WHAT WE'RE DOING
$client = new Google_Client();
$client->setApplicationName("My Calendar");
$client->setDeveloperKey('my_api_key');
$cal = new Google_Service_Calendar($client);
$calendarId = 'my_calendar_id';
//TELL GOOGLE HOW WE WANT THE EVENTS
$params = array(
'singleEvents' => true, //CAN'T USE TIME MIN WITHOUT THIS, IT SAYS TO TREAT RECURRING EVENTS AS SINGLE EVENTS
'orderBy' => 'startTime',
'timeMin' => date(DateTime::ATOM),//ONLY PULL EVENTS STARTING TODAY
);
$events = $cal->events->listEvents($calendarId, $params);
$count = 0;
$items_to_show = 3;
$data = array();
foreach ($events->getItems() as $event)
{
if($count <= $items_to_show)
{
//Convert date to month and day
$eventDateStr = $event->start->dateTime;
if(empty($eventDateStr))
{
// it's an all day event
$eventDateStr = $event->start->date;
}
$temp_timezone = $event->start->timeZone;
if (!empty($temp_timezone))
{
$timezone = new DateTimeZone($temp_timezone); //GET THE TIME ZONE
}
else
{
$timezone = new DateTimeZone("America/New_York"); //Set your default timezone in case your events don't have one
}
if ($count >= $items_to_show)
{
break;
}
$eventdate = new DateTime($eventDateStr,$timezone);
$data[$count]['newmonth'] = $eventdate->format("M");
$data[$count]['newday'] = $eventdate->format("j");
$data[$count]['newtime'] = $eventdate->format("g:i A");
echo json_encode($data);
++$count; //INCREASE COUNT AND START AGAIN.
}
}
?>
Here is my JSON array (there are only 3 events on the calendar) but it looks like it duplicates or resets everytime it looks for more:
[{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"},{"newmonth":"Jan","newday":"18","newtime":"3:00 AM"}]
Here is my JQuery that I want to display in the HTML automatically:
$(document).ready(function()
{
function load()
{
$.ajax
({
type: 'GET',
url: 'googlesidebar.php',
// data: {key: 'value'},
dataType: 'json',
success: function(data)
{
console.debug(data);
for (var i = 0; i < data.length; i++)
{
$('.newmonth').append(data[i].newmonth),
$('.newday').append(data[i].newday),
$('.newtime').append(data[i].newtime)
};
setTimeout(load, 5000);
},
error: function(data)
{
//called when there is an error
console.log(data.message);
}
});
};
load();
});
HTML Markup:
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="newmonth"></div>
<div class="newday"></div>
<div class="newtime"></div>
<footer>
</footer>
<script src="ajax.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Any help would be greatly appreciated!
I am trying to get the URL for all the photos of a facebook page.
How do I get the 'source' URL for this query and JSON structure:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=19292868552%3Ffields%3Dalbums.fields(photos.fields(source))&version=v2.1
I am using this success callback from a JSONP request:
function(response) {
for (i = 0; i < **???response.albums.data.length???**; i++) {
alert(**???response.albums.data[i].photos.data[i].source???**)
}
}
Can you help me find the right structure for the parts with the astericks? Because it has two [i]'s i think i'm getting confused..
You need to make sure that you have this in your head:
<script type='text/javascript' src='//connect.facebook.net/en_US/sdk.js'></script>
<script type='text/javascript' src='workFromPage.js'></script>
Now on workFromPage.js
var pre = onload;
onload = function(){
if(pre)pre();
if(!FB)reload();
var photoURLs = [];
// change userId
// make sure you test for login and wrap around code below, if needed
FB.api('/userId/albums', function(resp){
if(resp && !resp.error){
for(var i in resp){
FB.api('/'+resp[i].id+'/photos', function(r){
if(r && !r.error){
for(var n in r){
photoURLs.push(r[n].source);
}
// access photoURLs here
}
}
}
}
}
}
I have a piece of code in a view as
#if (Model.Count() > 0)
{
var locations = new List<string>();
var count = 1;
foreach (var shop in Model)
{
locations.Add(string.Format(
#"{{
title: ""Shop Name: {0}"",
position: new google.maps.LatLng({1}, {2}),
icon: ""{3}""
}}",
shop.ShopName,
shop.Location.Latitude,
shop.Location.Longitude,
count
)
);
count++;
}
var locationsJson = "[" + string.Join(",", locations.ToArray()) + "]";
}
How can I assign the locationsJson to a javascript variable as
<script type="text/javascript">
var jsLocations = #locationsJson;
</script>
Perform your embedded server code ON the server side instead, and then you could make it a property of the model and do something like:
<script type="text/javascript">
var jsLocations = #Model.locationsJson;
</script>
I have a piece of code in a view as
You absolutely should never have such piece of code in your view. Try this (shorter, better, safer):
<script type="text/javascript">
var jsLocations = #Html.Raw(Json.Encode(Model));
$.each(jsLocations, function(index, item) {
// TODO: do something with the item, for example
// alert(item.ShopName); or alert(Location.Latitude);
});
</script>
Your code will work fine.
However, you need to escape the values in your JSON, or you'll have an XSS hole.
You should use a real JSON serializer.