I have set up a function and a callback to retrieve some data regarding weather alerts. For some reason the data comes back as 'UNDEFINED'. I'm fetching the data through json although I would prefer to... fetch XML and callback json, however fetch and return json is fine.
Below is my code, but I have put it into a jsfiddle to make it easier to read.
http://jsfiddle.net/seversides/G7Wr8/
Javascript
$(function () {
// Specify the location and Api key
var apiKey = 'myapikey';
var location = 'zmw:00000.1.16172';
// Run the query (pull data from feed)
var url = 'http://api.wunderground.com/api/' + apiKey + '/alerts/q/' + location + '.json';
window['wCallback_3'] = function(data) {
// Get any weather alerts
var info = data.alerts;
// Warning level and color
$('#wWarning .wLevel').append('<TD>' + info.wtype_meteoalarm + '</TD>');
$('#wWarning .wColor').append('<TD>' + info.level_meteoalarm_name + '</TD>');
};
// Callback
$.ajax({
url: url,
dataType: 'jsonp',
contentType: "application/json",
cache: true,
jsonpCallback: 'wCallback_3'
});
});
HTML
<div id="wWarning">
<table class="wBox">
<h1 class="wLevel"></h1>
<h1 class="wColor"></h1>
</table>
</div>
When I run the code it displays the data as UNDEFINED. Why isn't it retuning the right data?
The "UNDEFINED" is referring to the callback function, because it doesn't exist as part of the request.
You're telling it that you want the output to be in JSONP in the line:
dataType: 'jsonp',
But that API is responding with JSON (excluding a callback).
In order to access it cross domain with JSONP (which is the right protocol for what you're looking for), you need to use the AutoComplete API:
http://www.wunderground.com/weather/api/d/docs?d=autocomplete-api&MR=1
Then, you set the callback with cb=myCallback in the GET string:
http://autocomplete.wunderground.com/aq?format=JSON&query=Anchorage&cb=myCallback
The problem is, I don't see any way in that API to use the zmw= values, so you may need a workaround for the area of interest.
Related
I'm trying to send the data I gathered from my web app to a google spreadsheet.
I'm using the script from Martin Hawksey:
https://gist.github.com/mhawksey/1276293
I've set it up and did everything as shown in the manual. And I am getting data back, but it's showing up as undefined values:
This is the code I use to send the JSON string to my spreadsheet:
function sendData(){
var url = 'https://script.google.com/macros/s/AKfycby3SUJvfEjdHWVoEON0L5hN4uXod8M4Jv1LAIWH3Ny16MIUz9o/exec';
var data = JSON.stringify(member);
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: function (response) {
console.log("succes! I sent this: " + data);
console.log("got this back: " + JSON.stringify(response));
},
});
}
This gives me a success message, it even tells me which row it was placed on.
This is the JSON string I'm sending:
{"Voornaam":"Name","Achternaam":"Name","Mail":"x#x.com","Verjaardag":"0/0/0000","Foto":"https://graph.facebook.com/xxxxx/picture?width=1020","School":"School X","Richting":"Course X"}
I even checked this JSON with a JSON parser online and it didn't return any errors.
For starters, I'm not entirely sure how to check which string I'm receiving at my spreadsheet. If it's still correct when it arrives. I tried logging it, but can't seem to get any response from the google logger.
If anyone could point out what I'm doing wrong, you would be greatly appreciated!
The Web script expects a JSON object. However, Ajax call is made with a string using the stringify function
var data = JSON.stringify(member);
Modifying the script to make the GET call with JSON object as is resolved the issue, like so
var data = member;
Typing this into the browser automatically downloads a txt file that is json formatted text of AAPL stock option data.
http://www.google.com/finance/option_chain?q=AAPL&output=json
I'd like to pull this data into a Javascript variable directly though, so I can parse the results and display the data in the browser.
I tried:
$.getJSON('http://www.google.com/finance/option_chain?q=AAPL&output=json', function(json) {
console.log(json);
});
but I get the No 'Access-Control-Allow-Origin' header is present on the requested resource. error, as seen in other posts.
I tried with ajax as well:
$.ajax({
dataType: "json",
url: "http://www.google.com/finance/option_chain?q=AAPL&output=json",
}).done(function ( data ) {
console.log(data);
});
but get the same error.
I also tried with jsonp (&output=jsonp) in the url, but get a Uncaught SyntaxError: Unexpected token ) error and it returns (); in Chrome inspector.
How can I pull this json data from Google directly into JS?
I'm sure there's a better way to do it... but it works.
First, to resolve the cross domain request you can use YQL.
Then, the url answer is not a valid json string. So I'm using "eval" to execute the response text and store it in the tmp variable.
function toYQL(site){
return 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent('select * from html where url="' + site + '"') +
'&format=json&callback=?';
}
$.ajax({
dataType: "json",
url: toYQL("http://www.google.com/finance/option_chain?q=AAPL&output=json"),
success: function(response){
eval("var tmp=" + response.query.results.body);
console.log(tmp);
}
})
There you go.
I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.
I am working with an API from another website and I am trying to get a JSON object back. Unfortunately due to the site origin issue I have to use JSONP to retrieve my data.
The function is working but I am stack on how to sanitize the data coming as a JSONP format to be able to use it as JSON?
This is my function
$('.loginForm').click(function(){
var url = 'https//api.example.com';
$.ajax({
type:'GET',
url: url,
dataType: 'jsonp',
error: jsonpCallback,
success: jsonpCallback,
jsonp: "callback"
});
function jsonpCallback(response){
console.log(response);
}
});
EDIT
This is the response I get before the error
Object { readyState=4, status=200, statusText="success", more...}
And this is the error i'm getting
SyntaxError: missing ; before statement
{"accountID":1328031,"authToken":"D81CDCB......
I went through every post in SO and the web in general to find where I am making a mistake but so far I can't find anything.
If you are getting the response in jsonP then you can use jXHR for making cross domain request , below is the link of jXHR (Library) :
https://gist.github.com/1576277/f4aead6741e0d7b0c40db6601048d9db6be1a5f9
And here is an example to use jXHR :
function sendRequest()
{
var xhrReq = new jXHR();
xhrReq.onreadystatechange = function(data)
{
if (xhrReq.readyState === 4)
{
//data contains your jsonp response..
}
};
var url = "http://" + SERVER_NAME + "yourCodeFile.aspx?callback=?";
xhrReq.open("GET",url);
xhrReq.send();
}
Always remember to add 'callback=?' as a query string parameter in url for jXHR request as the respone is jsonP.
Hope this helps you.
try using JSON.parse
function jsonpCallback(response){
console.log(JSON.parse(response));
}
I have a web application with an HTML form. When I press submit I want to submit the values from this form to a perl script, parseDatabaseData_v2.pl, which get's data from a database and creates a JSON string of that data.
Then, I'd like to visualize this JSON data using a D3 graph.
The following code using jquery ajax works, and returns JSON from the perl script as expected.
var runFromDate = $('#runDateSelectBox1').val();
var runToDate = $('#runDateSelectBox2').val();
var barcode = $('#barcodesSelectBox').val();
var dataString = 'runFromDate='+ runFromDate + '&runToDate=' + runToDate + '&barcode=' + barcode;
// ajax command
$.ajax({
type: 'POST',
url: './cgi-bin/parseDatabaseData_v2.pl',
async: true,
data: dataString,
dataType: "json",
success: function(data) {
console.log("succesfully called script");
}
}); // end of ajax command
In the perl script I use cgi->param('runFromDate'); to get the posted parameters.
However, since I'm visualizing the data using NVD3's lineWithFocusChart I want to call the script using d3.xhr.
When I create the following d3.xhr request the script doesn't work (it get's called, but is unable to get the parameters).
var runFromDate = document.getElementById("runDateSelectBox1").value;
var runToDate = document.getElementById("runDateSelectBox2").value;
var barcode = document.getElementById("barcodesSelectBox").value;
var dataString = 'runFromDate='+ runFromDate + '&runToDate=' + runToDate + '&barcode=' + barcode;
d3.xhr("./cgi-bin/parseDatabaseData_v2.pl")
.header("Content-Type", "application/x-www-form-url-encoded")
.post(dataString,function(error, data){
console.log("succesfully called script");
console.log(data);
});
I've tried various ways of formatting the datastring including formatting it as JSON as explained at the D3 API Reference.
I'd be most grateful if someone was willing to help me with this.
Thanks,
Koen
You have a spurious hyphen between url and encoded!
Change
.header("Content-Type", "application/x-www-form-url-encoded")
to
.header("Content-Type", "application/x-www-form-urlencoded")
Looks like you are not the only one as this other recent answer shows. Seems the offending code has been in the d3.js wiki so I have updated it too.