I want to be able to pull data from a google spreadsheet doc every 24hrs and use the values in my html page.
I have managed to get the JSON url for the cell I want to track, but I do not know how to get this JSON object into a javascript variable using the url.
I have searched around and tried using Jquery $.get() and $.getJSON() but I cant seem to get anything to work.
The url for the google spreadsheet data cell JSON is
https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS
I know this is probably simple but I am very new to working with JSON/ Javascript and have been struggling to work this out.
Thanks for any help :)
The data being returned is jsonp so you need to specify that in your Ajax request.
function getData() {
return $.ajax({
url: 'https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS',
dataType: 'jsonp',
jsonpCallback: 'importGSS'
})
}
And while you can assign the data to, say, a global variable this will only get you so far - the Ajax process is asynchronous and you won't be able to access the data until the process has finished:
var obj;
getData().done(function (data) {
obj = data;
});
// console.log(obj) here will return undefined as the process
// has not yet finished
Much better to grab the data and do something with it:
function doSomethingWithData(data) {
console.log(data);
}
getData().done(function (data) {
doSomethingWithData(data);
});
Or even simpler:
getData().done(doSomethingWithData);
Related
I am writing a JS where I want to make some Ajax calls to get a JSON file from my DB in CouchDB. My code is based on examples I found online, but my lack of experience and knowledge is making it difficult to fix it completely.
My code:
function myFunction(){
var request = $.ajax({
url:'http://admin:pass#localhost:5984/db/_design/view/_view/view',
type:'get',
dataType:'json'
});
request.done (function (data)){
var result;
for (var i in data){
if( data[i] == key){
result.push(data[i]);
}
}
console.log(result);
};}
Problem: It seems like it is not even doing the requested call since when I try to print my array it isn`t doing anything.
The way see it, in the first part where I defined request it should get the JSON file from CouchDB. And, if correct, in the second part where the request is done request.done I give the function how I want the JSON file to be taken care of. To make it clear, my idea is to iterate through the data and to save the values of the "key" in every row in my result-array.
TL;DR: Any good examples of using AJAX, d3 and PHP to get data from a database and produce graphs from it would be greatly appreciated.
So I'm using d3 to create a force chart based on data pulled from a database using AJAX and PHP, I think there's a few ways to do this, either binding the data to a DOM element, or using D3.queue seem to be the most logical ways to do it, but I'm struggling to find simple examples of using all these bits together.
So my working AJAX request looks like this:
$(document).ready(function() {
$('select[name="locations"]').change(function(){
var location = $(this).val();
$.ajax({
type: 'POST',
url: 'dataselect.php',
data: { l_id: location },
success: function (response) {
console.log(response);
},
});
});
});
I've tried passing the JSON to a DOM element, but no luck extracting it and some people seem to dislike this approach.
The d3 that works looks like this:
d3.json("test.php", function(error, graph) {
if (error) throw error;... Lots more d3 that I don't think is relevant.
test.php and dataselect.php are identical except dataselect has a variable for the AJAX request and the d3 doesn't like it as it is.
So, my question is what is the smoothest way for d3 to "wait" for the data from the AJAX request before running?
I'm guessing I need to wrap some stuff in functions and queue it into some kind of order, but I'm really struggling to tie it together.
Finally, sorry I feel like this should be fairly trivial, but I have read a lot of questions and haven't managed to implement any solutions so far.
EDIT: So following the d3.request route, I've figured out how to send the data without AJAX:
d3.selectAll("#onploc")
.on('change', function() {
var location = eval(d3.select(this).property('value'));
console.log(location);//gets value property of selected menu item.
d3.json("dataselect.php?l_id="+location,function(error, data) {
console.log(data);//sends location variable to php to get data back.
})
});
This could go either way - you could either call the d3 drawing code from your success callback, e.g.
...
success: function(response) {
var data = JSON.parse(response) // maybe, if you need to convert to JSON
d3RenderFunction(data);
}
or you could pass the parameters using d3.request:
d3.request('dataselect.php')
.mimeType("application/json")
.response(function(xhr) { return JSON.parse(xhr.responseText); })
.post({ l_id: location }, function(error, graph) { ... })
I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.
"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there
what I need to do is read the content of a "public" google spreadsheet (by public I mean that I saved the sheet clicking on "File > Publish to the web", so it's accessible without the need to be logged in into a google account), and, why not, write something into it too.
googlin' around, I found that I can access the sheet and get the xml equivalent of the sheet content with something like
https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values
It works great if I load that url into a browser. But I need to find a "javascript-way" to get and handle the returned value, ie the xml (or json, but xml would be preferable).
I tried to use an ajax call, but I think there's something messy with the protocol.. I can't get the server response correctly.
$.ajax({
type: "GET",
url: "https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values",
success: function(data){alert("yeah");},
error: function(){alert("fail..");},
dataType:"xml",
});
I also tried to get the json instead of xml, adding "?alt=json" to the url and changing the datatype, but I still have the problem..
Any idea / suggestion?
Thanks in advance, best regards
You need to request with a JSONP call and you need to specifiy a callback - method. This can be done in jQuery using:
var url = 'https://spreadsheets.google.com/feeds/list/<CODE>/od6/public/values?alt=json-in-script&callback=?';
jQuery.getJSON(url).success(function(data) {
console.log(data);
}).error(function(message) {
console.error('error' + message);
}).complete(function() {
console.log('completed!');
});
Documentation and samples for google spreedsheets .