First off, apologies if this is a silly question, I'm new to WinJS and relatively new to Javascript, but I've been going great til I hit this roadblock.
I'm currently working on a weather app for Windows 8 using WinJS, and I'm trying to pull the data from the forecast.io API, which in my case is provided in JSONP format.
I easily got it working in-browser using jQuery and .getJSON, but since I have to use WinJS.xhr to request the data instead I'm having some difficulty.
I can pull the data just fine using the following code:
function getWeather() {
WinJS.xhr({
type: "GET",
url: "https://api.forecast.io/forecast/*ommited API key*/-36.044394,146.953718?callback=?&units=si",
headers: { "Content-type": "application/json" }
}).then(function complete(data) {
var weatherData = data.responseText;
(new Windows.UI.Popups.MessageDialog(weatherData, "Success!")).showAsync().done();
}, function error(data) {
(new Windows.UI.Popups.MessageDialog("Failed.", "Error")).showAsync().done();
});
}
This shows me the data in a popup window, so I'm sure that I've accessed it. The problem is, I can't do anything with it. In jQuery I simply used "data.currently.temperature" to get the current temperature data, but I can't get something similar working in this situation.
Any help or pointers would be greatly appreciated!
P.S sorry if I butchered any terminology, I'm doing my best.
Here's what data.responseText returns, there's quite a lot so I put it in a text file.
http://justadddesign.net/data.responseText.txt
It's because data.responseText is string not object. Try:
var forecastInfo = JSON.parse(data.responseText);
and then access forecastInfo object properties.
Related
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);
I am currently stuck on a task in which I have to use jQuery ajax to retrieve messages from PARSE HERE API to create something like this:
http://chatbuilder.hackreactor.com/?example=1&username=aa
I was wondering if anyone could explain to me how to use REST api to retrieve messages.
I have looked at other people's coding examples:
https://github.com/stevernator/Chatbuilder/blob/master/draft11
and
https://gist.github.com/guymorita/5726564
They seem to use ajax code like below:
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: function(data) {
var stuff = [];
for(i=0; i < 10; i++) {
stuff[i] = data.results[i].text
}
My question is: from where are the messages being generated from in this app? Do I have to create an account at Parse or would I just use ajax to retrieve this url link:"https://api.parse.com/1/classes/chats"?
Also, where would I find info on this specific class (chats)?
Any input would be greatly appreciated. Thanks!
The parse quick start guide is a very good place to start. The documentation is really good but the tutorials for the JS API are far more complex (backbone) than the documentation. I would download the Todos tutorial as there is some good stuff in it but if you dont know how backbone works its harder to read. I would have made this a comment but I don't have enough rep :(.
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 .
I'm not a very experience programmer and have been learning HTML/CSS/JS on the fly. I've been trying to parse XML using jQuery AJAX methods with absolutely no luck.
Here is my code in use: http://jsfiddle.net/Kb5qj/1/
And here is my code in plain sight:
$(document).ready(function() {
var divid = "#xmlcontent"
function parseXML(xml) {
$(divid).empty();
$(xml).find("CD").each(function() {
var artist = $(this).find("ARTIST").text();
var title = $(this).find("TITLE").text();
$(divid).append("<li>" + artist + " - " + title + "</li>");
});
}
function printError() {
$(divid).html("An error occurred");
}
$.ajax({
type: "GET",
url: "www.w3schools.com/ajax/cd_catalog.xml",
dataType: "xml",
success: parseXML,
error: printError
});
});
I don't know what the problem could be. I have written and re-written and copy/pasted that $.ajax call many many times, but no matter what I do nothing ever happens. Help me please?
like I mentioned it will fail on jsfiddle as they dnt actually send the get request. here is the api on how to achieve the same: http://doc.jsfiddle.net/use/echo.html
If you try the same on your local system it will fail probably cos you are making a cross domain request and your browser natively blocks such requests. That is where jsonp comes it to play its to retrieve json data over cross domains..
You can hack it a little to do the same for js.. here is a SO post about the same: Is there an existing tool for jsonp like fetching of xml in jquery?
With a little bit of fudging, everything in the parsing seems to work fine. Check out this JSFiddle.
You can't use get requests from JSFiddle, but I mocked up the XML into HTML. You may want to try placing your XML document into the DOM to help suss your issue.
I am wanting to try and do a handful of things with the use of jQuery and Amazons S3 API via REST. My key issue is not being familiar with REST well enough (or not as well as I thought I knew) to know if this approach would even remotely work right. I have tried searching endlessly for some tidbit of an example and came up fruitless, maybe I am searching for the wrong things I don't know, but as a last ditch effort I figured I'd hit up my new favorite place, here..
What I need to do is send. PUT a request to the API to create the bucket. Based on the S3 API docs I came up with
var AWSAccessKeyId = "";
var AWSSecretAccessKey = "";
var AWSDomain = ".s3.amazonaws.com";
function createNewBucket(bucketName)
{
var bucketString = 'HTTP/1.1\n';
bucketString += bucketName + AWSDomain + '\n';
bucketString += 'Content-Length: 0 \n';
bucketString += 'Date: Wed, 01 Mar 2009 12:00:00 GMT \n';
bucketString += 'Authorization: AWS ' + sha1_string;
$.ajax({
url: bucketName + AWSDomain,
type: 'PUT',
data: bucketString,
success: function(data)
{
},
error: ''
});
}
though concept isn't complete with the above I am just starting it out, and I started questioning if this idea of approach was even going to work.. And if it is to work with the above or in any means provided here for help how would I also work with the response to know if it was successful or not? I know if I can nail this one piece down I can handle for the most part the rest of my issues to come. Its just tackling the first hump and figuring out if I am going about it the right way. Its also worth mentioning that I have been tasked with doing this purely javascript style with or without the help of a lib like jquery. I can't use PHP, or the like in this concept. So if anyone can throw me a bone i'd be greatly appreciative.
On a side note, does anyone know if theres a means of actually testing something like this stuff out without actually having a S3 account, cause I can't afford to pay for an account just for the sake of testing let alone any other reason.
Firstly, I am getting the feeling that you are quite new to consuming web-services client side.
It is often best to start with something simple.
If I have a resource that returns a string... say test.html -> "Hello World!"
And the URL for this web-service is some-realy-long-id.s3.amazonaws.com
then we have the following:
$.ajax({
url:'some-realy-long-id.s3.amazonaws.com/test.html',
type: 'PUT',
data: {
'myKey':'myValue'
},
success: function(data) {
//alert dialog containing "Hello World!"
alert(data);
},
error: ''
});
You must remember that requests from the browser follow the same-origin policy, so unless you are planning to use JSOP, or some other cross-domain hack you will run into trouble.
p.s. another little piece of advice is to use right hand braces in Javascript as it performs semi-colon insertion (which will bite you if you return a object literal).
Oh yes and a lot of old browsers do not support 'PUT' which you may need to consider.