Unable to get property 'query' of undefined or null reference - javascript

I am using Yahoo Weather API.
Here is my code:
<script>
var callbackFunction = function (data) {
console.log(data);
var location = data.query.results.channel.location;
var condition = data.query.results.channel.item.condition;
var wind = data.query.results.channel.wind;
var units = data.query.results.channel.units;
document.getElementById('Weather-Info').innerHTML = 'The weather for ' + location.city + ', ' + location.region + ' is ' + condition.temp + units.temperature + ' with a wind speed of ' + wind.speed;
}
callbackFunction()
<script src="https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20weather.forecast%20WHERE%20woeid%3D%222409681%22%20and%20u%3D%22f%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=callbackFunction"></script>
Everytime I go into the page I receive the following pop-up:
Unable to get property 'query' of undefined or null reference
But if I hit No, the data is still populated.. how is it populating data if it is telling me that a property is undefined? The YQL Weather API is a really complicated.

Why are you calling the callback function yourself? In any case, calling it without a parameter, means that data will be undefined and this is why you get the error.
I know nothing about Yahoo! weather API but this seems like a JSONP thing, so try removing this part:
callbackFunction()
since this will be called automatically once the script loads.

Related

How do I convert an entire website to a string that I can parse using javascript?

So I am making a website for my video game servers and our admin tool outputs the current server status as a .json in a giant string of text to this url:
http://server.bandwidthbandits.org/api/status
I want to take the entire string from the url and assign it to a var so I can use JSON.parse() with the string obtained from the link. In other words how do I convert the entire aforementioned web page into a long string I can parse with javascript?
I have no idea how to do that, but I'm pretty sure I can parse the JSON once it's in a string.
This is what I thought might work, but it didn't:
p id="SERVERS">HELLO</p>
<script type="text/javascript">
var txt = document.getElementsByTagName('http://server.bandwidthbandits.org/api/status')[0].innerHTML;
var obj = JSON.parse(txt);
document.getElementById("SERVERS").innerHTML = obj.name + ", " + obj.map + ", " + obj.gamemode + ", " + obj.players;
//more parsing necessary, but to tired to write full statement right now
</script>
UPDATED CODE:
<p id="name">HELLO</p>
<p id="maxp">HELLO</p>
<p id="curp">HELLO</p>
<script type="text/javascript">
function FetchAPI(url) {
fetch(url).then(function (data) {
return data.json();
}).then(function (obj1) {
console.log(obj1);
});
}
var nukestats = FetchAPI("http://server.bandwidthbandits.org/api/status/340417768");
obj = JSON.parse(nukestats);
document.getElementById("name").innerHTML = 'Server name: ' + (obj[0].name);
document.getElementById("maxp").innerHTML = 'Max Players: ' + (obj[0].maxPlayers);
document.getElementById("curp").innerHTML = 'Current Players: ' + (obj[0].currentPlayers);
</script>
The updated code shows what I tried to do. Since there will be multiple servers that I will have to query I tried to make the fetching of the API into a function. The problem I face is that I don't know how to import the API from the web into something I know how to parse through. If I copy and paste the API output into my code as a variable it works, but it does not work when I try to import the API using java script.
You need to fetch the data from the site and using promises, parse it:
fetch("http://yourapi.com").then(function (data) {
return data.json();
}).then(function (obj) {
console.log(obj);
});
What you are looking at is not an actual website by the way. The API returns a json string and since the browser can't really do anything else with it, it will just display it as text.
You have to get response using ajax call with data type application/Json
Or Directly use below jquery method:
$.getJSON(url,function(data){
//Here you get json on data variable
});
But make sure your url will return json string.

Cordova app has internet connection via emulator, but not on device [update: ajax problem]

I am trying to build a small app via cordova that sends data to a PERL-Script on a server. The debug and release build work fine on the genymotion emulator, however sending the data from Android phones does not work. There is no error message from the app (either, which is supposed to show up when the connection fails).
Running USB debugging, I do get the follwoing invoke error message (the savedataLastpage funtion is supposed to send the data):
Uncaught TypeError: Illegal invocation
at e (jquery-2.1.3.min.js:4)
at Ac (jquery-2.1.3.min.js:4)
at Function.n.param (jquery-2.1.3.min.js:4)
at Function.ajax (jquery-2.1.3.min.js:4)
at Object.saveDataLastPage (index.js:631)
at Object.renderLastPage (index.js:461)
at Object.recordResponse (index.js:597)
at HTMLButtonElement.<anonymous> (index.js:357)
at HTMLButtonElement.dispatch (jquery-2.1.3.min.js:3)
at HTMLButtonElement.r.handle (jquery-2.1.3.min.js:3)
The pertaining code is the following:
index.js:631
saveDataLastPage:function() {
$.ajax({
type: 'post',
url: '/URL/',
data: localStore,
crossDomain: true,
success: function (result) {
var pid = localStore.participant_id, snoozed = localStore.snoozed, uniqueKey = localStore.uniqueKey, pause_time=localStore.pause_time;
localStore.clear();
localStore.participant_id = pid;
localStore.snoozed = snoozed;
localStore.uniqueKey = uniqueKey;
localStore.pause_time=pause_time;
$("#question").html("<h3>Thank you, your responses have been sent.</h3>");
},
error: function (request, error) {
console.log(error);
$("#question").html("<h3>Error: Please check your internet connection.</h3><br><button>Send again</button>");
$("#question button").click(function () {app.saveDataLastPage();});
}
});
},
index.js:461
else {
var datestamp = new Date();
var year = datestamp.getFullYear(), month = datestamp.getMonth(), day=datestamp.getDate(), hours=datestamp.getHours(), minutes=datestamp.getMinutes(), seconds=datestamp.getSeconds(), milliseconds=datestamp.getMilliseconds();
localStore[uniqueKey + '.' + "completed" + "_" + "completedSurvey" + "_" + year + "_" + month + "_" + day + "_" + hours + "_" + minutes + "_" + seconds + "_" + milliseconds] = 1;
app.saveDataLastPage();
}
As stated before, on the genymotion emulator the ajax script works fine without the error and sends the data to the script.
I'm not sure why the emulator would work just fine but the error Uncaught TypeError: Illegal invocation suggests that it is a problem with the ajax post call. Specifically, the default setting of processing the data into a query string likely fails.
From the ajax documentation:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
That means you can either turn off the processing processData: false which will post the data in the body of the request or you have to transform the localStore data into a proper object (from whatever it was before).
If it is like an object you can do the following:
var data = {};
for (var elem in localStore) {
data[elem] = localStore[elem];
}
or possibly in brief:
var data = {};
localStore.each(function(elem) { data[elem.name] = elem.value; });

How do I load data from an external URL using JSON?

I want to display a name from this url http://api.open-notify.org/astros.json/
Here is my code,
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.results[0].formatted_name;
console.log('Name : ', name);
});
I want to display it with my h3 tag. I'm new to JSON and jQuery. I keep getting
index.html:631 Uncaught TypeError: Cannot read property '0' of undefined error
You have to use the success() or done() function.
var url = "http://api.open-notify.org/astros.json/";
$.getJSON(url).success(function (json) {
var name = json.people[0].name
console.log('Name : ', name)
})
If you are able to reach out to the specific endpoint and not be blocked by CORS it must be the format of the data.
Looking at the data, there is no property called results in your data. Try debugging that line to see the proper format of the variable json. It may be a string and you would need to call JSON.parse(json); in order to format it properly as an object.
You should be able to do:
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.people[0].name;
console.log('Name : ', name);
});

How to get JSON after geolocation in JavaScript/jQuery?

I'm building a project that finds the geolocation from the browser, then uses the coordinates to get data from the Dark Sky API (https://darksky.net/dev/).
I am able to get the geolocation from the browser, but am having trouble calling the JSON object once I get the geolocation. I understand that getting the geolocation is "asynchronous" and runs at the same time as my other code, and I can't seem to figure out a way around it.
Am I'm doing something wrong? It never seems to runs the: $.getJSON part.
All the #test htmls are for my reference to see where my code is going wrong. #test4 never runs, but #test3 does.
P.S. I've kept the API key hidden for my question, hence the KEY characters in the url. The myJson variable does concatenate a proper url to retrieve the JSON object.
Any help would be deeply appreciated!
var myLat;
var newMyLat;
var myLong;
var newMyLong;
var myJson;
var functionCall;
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLat = position.coords.latitude;
myLong = position.coords.longitude;
newMyLat = parseFloat(myLat).toFixed(4);
newMyLong = parseFloat(myLong).toFixed(4);
$("#test1").html("latitude: " + newMyLat + "<br>longitude: " + newMyLong);
myJson =
"https://api.darksky.net/forecast/KEY/" +
newMyLat +
"," +
newMyLong;
$("#test2").html(myJson);
getJsonData();
}); // end of getCurrentPosition function
} // end of navigator.geolocation function
}); // end of document.ready function
function getJsonData() {
$("#test3").html("getJsonData called");
$.getJSON(myJson, function(data) {
$("#test4").html("JSON retrieved");
}); // end of .getJSON function
} // end of getJsonData function
Answer that worked for this situation:
I just needed to add ?callback=? to the end of my JSON url, making it:
myJson = "https://api.darksky.net/forecast/ee2f66f091ed810afc3bf04adc5fa750/" + myLat + "," + myLong + "?callback=?";
Thank you for all the help!

Add A Table Row With Ajax Results

I have a function that takes the values returned from an ajax call and adds a row to a table that is defined in the json values, but I don't think it is fetching the table correctly. Is there anything special I need to be doing? I know the data['table_name'] variable does have the correct value in it.
Here is the code I have.
function ajaxSuccess () {
var data = JSON.parse(this.responseText);
var elementObj = document.getElementById(data['table_name']);
var i = elementObj.size() + 1;
elementObj.append('<tr><td>Date</td><td>Name</td><td>' + data['new_comment'] + '</td></tr>');
i++;
return false;
}
This is not correct.
You have js variable var elementObj = document.getElementById(data['table_name']);
And you use jquery append().
Try var elementObj = $("#"+data['table_name']); instead.
Also check console for errors, you are probably receiving this:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'append'
p.s. you can also try this:
$(elementObj).append('<tr><td>Date</td><td>Name</td><td>' + data['new_comment'] + '</td></tr>');
without rewriting var elementObj to jquery variable.

Categories