I've been trying to write a program in JavaScript that can retrieve weather data from OpenWeatherMap using JSON. I'm pretty new to JSON, but I think that I understand the logic behind it. However, when I click the "Get JSON" button, nothing happens. It's possible that "data.temp" in the getJSON function is incorrect, but if I'm understanding correctly, it seems like it should at least print the word "Temperature:" HTML and JavaScript are enclosed below, any help is appreciated.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<div id = "owmData" style = "background-color:#cc0;">
Weather data should go here.
</div>
Get JSON
JavaScript:
$(document).ready(function() {
/* Operate when "getIt" button is clicked.*/
$("#getIt").click(function(event){
/* Variable storing weather information.*/
var weatherNow="http://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=******************";
$.getJSON(weatherNow,function(data){
$('#owmdata').append('<p>Temperature : ' + data.temp+ '</p>');
});
});
});
In your request parameters you are specifying "test" as the callback function. You can strucuture your request url like this without the ref to the callback and access the data directly:
http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=*************
"temp" is nested inside of the property "main" so you would reference it as data.main.temp
Related
Edit/Clarification: I have a php page, call it displayPhotos.php, in which I set up an Ajax call to a different php page, call it getPhotos.php, which queries a database and returns photo information (caption, file name etc) to displayPhotos.php where they are displayed. I use php in displayPhotos to manipulate the data returned from getPhotos. The returned data from the Ajax call is a javascript 2-dimensional array. I need to turn the javascript array into a php array so I can do they display and other stuff. How do I do that?
Hope this helps.
My eyes hurt from reading all of the docs.
I want to use ajax to query a database, return the data then use php to continue with the web page.
All of the examples I've looked at start with creating the json in php. I need to start with the json object in javascript.
<script>
var photoarray = [];
var ajaxRequest = $.ajax
({
url : "fhs_get_photos.php",
type: "POST",
dataType: "json",
success: function(photo_array)
{
photoarray = photo_array;
//line below works. the file name is correct but disappears
//outside of this function
console.log("photoarray[0][file_name] is: " + photoarray[0]['file_name']);
},
error: function(request, status, error)
{
alert('An error occurred: ' );
}
});
In this instance I'm not passing anything to the php file that query's the db. The console log shows that the file name in photoarray is correct but once outside of this function it disappears even though it's declared as global, I think it is anyway. Why and what do I need to do to fix this.
The php file just does a SELECT * FROM..... and returns everything.
// in fhs_get_photos.php
// SELECT * FROM table......
echo $json = json_encode($result);
return $json;
So I now have the array back but it's in javascript. Once I figure out the scope problem, how can I convert this javascript array to a php array?
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<figure id="photo_figure">
<script>
//line below gets me: SCRIPT5007: Unable to get property 'thumb' of
//undefined or null reference
console.log("photoarray thumb: ") + photoarray[0]['thumb'];
</script>
Am I explaining this properly?
First of all AJAX is async. This means it sends the request when you ask it to, but receives the response sometime later in the future. And it works after php has rendered and sent the page. So. When you get an update via AJAX, you have to use javascript to make that update matter. The most simple solution is to process the response right there in the success callback. That way you don't need to mess with the global scope (which is a bad practice).
Supposedly, your HTML is like this:
<header>
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<div id="figures"></div>
You can do it by declaring a function that handles the processing:
function updateDom(photoArr) {
var $figures = $('#figures');
$.each(photoArr, function() {
console.log(this);
$figures.append('<img src="' + this.thumb +'">');
});
}
Code below is placed in the success callback
And execute that function in the success callback and pass it the array from json, that was parsed and became a valid js object.
var photoArray = JSON.parse(photo_array);
updateDom(photoArray);
here's the fiddle, but it's for the DOM part only
First of all, forgive me if any of this code is bad, inefficient, or completely wrong, I haven't worked with JSON at all before, or any sort of API work.
So, I'm just trying to create a basic webpage which will display some information from the JSON obtained through JSONP (did I implement it correctly...?). I thought that I was accessing the id element correctly but it seems not as I've tried getting it to show up with alert, console.log, and setting the inner html of the paragraph. Here is the code:
HTML
</head>
<body>
<p id="main">
test
</p>
</body>
<script src="js/parseJSON.js"></script>
<script type="application/json" src="https://www.aviationweather.gov/gis/scripts/MetarJSON.php?taf=true&bbox=-86,41,-82,45&callback=parseJSON"></script>
</html>
Javascript
var parseJSON = function(json) {
var obj = JSON.parse(json);
console.log(obj.features[0].properties.id);
}
This seems like something simple I'm just screwing up. Any help would be appreciated, thanks!
I'm just trying to create a basic webpage which will display some information from the JSON obtained through JSONP (did I implement it correctly...?).
You said type="application/json" so the browser ignored it because it doesn't know how to execute scripts written in JSON.
JSONP is not JSON, it is JavaScript, so the correct Content Type is application/javascript.
Further https://www.aviationweather.gov/gis/scripts/MetarJSON.php?taf=true&bbox=-86,41,-82,45&callback=parseJSON returns JSON not JSONP.
var parseJSON = function(json) {
var obj = JSON.parse(json);
While it is possible for a JSONP service to provide data in the form of a JavaScript string containing JSON, that is never something I've seen. The argument should not be parsed as JSON. It should be a regular JavaScript data structure.
… but first you need the service to return JSONP.
I am trying to parse some data from a source that is formatted like this:
var = jsonReturnData = {}
instead of this:
jsonReturnData({})
If I read the file using a script tag like this:
<script src="http://foundationphp.com/phpclinic/podata.php?startDate=20150301&endDate=20150302&raw"></script>
I have no problem reading the data, but if I try to do any sort of JSON or JSONP call from within jQuery, I either get an error or no access to the data depending on how I do it.
$.getJSON('http://foundationphp.com/phpclinic/podata.php?startDate=20150301&endDate=20150321&raw', function(data) {
console.log(jsonReturnData);
});
I need to be able to load the data dynamically when someone chooses some dates. Here's a sample of the interface working, but with no access to the JSON file. The data that you see is being read by the script method.
http://iviewsource.com/exercises/codeclinic/01/
How do I extract the data below. I only want to print out the value number after "networkdiff" in this API.
This is the URL for the API from a different website:
http://21.luckyminers.com/index.php?page=api&action=getpoolstatus&api_key=8dba7050f9fea1e6a554bbcf4c3de5096795b253b45525c53562b72938771c41
I want the code to automatically retrieve the data from the URL above, and display the value after "networkdiff" to display on my other webpage.
Here's my code so far that I will put in my own webpage:
<HTML>
<body>
<script>
I don't know what I should put in this script part.
</script>
</body>
</html>
Below is the data the URL showed up as:
{
"getpoolstatus":{
"version":"1.0.0",
"runtime":10.684967041016,
"data":{
"pool_name":"21 Coin Pool # Luckyminers.com",
"hashrate":0,
"efficiency":97.79,
"workers":0,
"currentnetworkblock":0,
"nextnetworkblock":1,
"lastblock":40544,
"networkdiff":1,
"esttime":0,
"estshares":4096,
"timesincelast":1240429,
"nethashrate":0
}
}
}
Since the data is coming from an external domain, you can't use Ajax to get the data, unless the server enabled CORS. This doesn't seem to be the case, but it seems to support JSONP:
<script>
function processResponse(data) {
console.log(data);
}
</script>
<script src="http://21.luckyminers.com/index.php?page=api&...&callback=processResponse></script>
The callback=parseResponse makes the server return JS consisting of a function call to processResponse. How to access the information you actually want is explained in Access / process (nested) objects, arrays or JSON.
You need to include JSON.js in your web page to use JSON function in javascript. Here is the URL for download
https://github.com/douglascrockford/JSON-js
And then you can use beloe code to parse the JOSN string into javascript object.
var objectJSON = JSON.parse(jsonStr);
You can alse used stringify fucntion to the viceversa.
In which way you call the JSON?
You can call it with a callback function (working example), including it as a script:
updateResult=function()
{
var s=document.createElement('script');
s.src=domain+"/index.php?page=api&callback=showResult&action=getpoolstatus&api_key="+api_key;
document.body.appendChild(s);
}
You must have the callback defined like:
showResult=function(data)
{
document.getElementById('result').innerText=data.getpoolstatus.data.networkdiff;
}
If you call it with JQuery and get the JSON object, you can define the callback in the argument like the following example, but you must have same-origin (your script must run with the same domain (21.luckyminers.com in this case):
$.getJSON(
domain+"/index.php?page=api&action=getpoolstatus&api_key="+api_key,
function(data)
{
document.getElementById('result').innerText=data.getpoolstatus.data.networkdiff;
}
);
But in any case, be careful. Where did you get the API key? If you put it on a client-side script (like JavaScript) anybody can read the key, and with that key maybe do some damage… :S
I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks