I've been battling with this seemingly simple issue for a good two hours now.. Please educate me. I just don't undestand what I'm doing wrong.
I have a PHP script that I call from a react component with a $.get function like so:
this.serverRequest = $.get("php/get_house.php", {"id":this.props.houseId}, function(data){
this.setState({house: data, loading: false});
}.bind(this));
I then pass the data in this.state.house into another component :
<ShowHouse house={this.state.house} />
In ShowHouse component I log the data:
console.log(this.props.house);
console.log(this.props.house[0]);
The first one returns something that chrome console shows as [{...}], with the data in 0:nth position, the second one returns what you'd expect - just the data in normal JSON format like in the block below.
My JSON that I get printed on the page if I simply open the PHP-script with an id, like ..php?id=1
[{"heading":"Kuin uusi","id":"1","city":"Helsinki"}]
How do I access this data? I get an error "Cannot read property 'heading' of undefined" if I simply try to access it by
console.log(this.props.house[0].heading).
You can use array syntax
this.props.house[0]["heading"]
Related
I'm trying to load a JSON file by link and then align data (like title, date etc) to variables so I can use them. Right now, I don't care about variables. I just want to alert() them but something seems like I'm doing it wrong, alert returns nothing!
I use JSfidle to run the code. The code is this:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json') ;
var JSON = JSON.parse(JSON_unparsed) ;
alert(JSON.feed.entry[0].title.$t) ;
The URL I want to parse is: http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json
and here you can see the JSON how is structured if that can help you:
You can use JSONP for this:
Update, for better understanding how to work with returned JSON.
var id, title;
$.ajax({
url: 'http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json',
jsonp: "callback",
dataType: "jsonp"
}).done(function(r){
// r is returned JSON
for(var i in r)
// for ex ID is this
id = r[i].id.$t;
// and title
title = r[i].title.$t;
// and so on, check the json, I mean check the browser console by hitting F12, below code will print the whole JSON
console.log(r[i]);
});
Codepen link: http://codepen.io/m-dehghani/pen/grXrrp?editors=0010
In addition to adeneo's reply, in your code, JSON_unparsed variable is holding something called (differed or promise object), this object might be holding the data inside it,but you are using the wrong way to pull it out. in order for you to get it out, you need to call (.done()) function, see the below:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json').done(function(json){
console.log(json);
console.log(json.feed.entry[0].title.$t);
});
aside from that, if you got an error with something like this:
XMLHttpRequest cannot load http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json&_=1459788714707. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.
it means that you are not allowed to call this API/URL from your current domain.
One more thing, if you are using getJSON method, there is no need to parse the returned data, jquery will parse it for you
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
I send a http GET request which returns JSON data in the following form. I am finding it impossible to access this data despite having no problems with example json that I create. I want to ideally take the array under wifi, and use this data to create a html table, but I think I can work out how to create the table if I could just access the actual elements of the data.
I have tried multiple methods to try and reach the first timestamp. I have tried:
var element = result.undefined.clients.wifi[0].timestamp;
but this returns an error that 'clients' can't be found.
I also tried:
var element = result.clients.wifi[0].timestamp; //and
var element = result.wifi[0].timestamp;
The JSON data returned to a variable is shown below:
result = undefined
{"sourceId":"idid","sourceType":"CLOUD_source","searchMeta":{"maxResults":4,"metricType":["clients"],"family":["wifi"],"Interval":"M1"},
"clients":{"wifi":
[{"timestamp":1424716920,"avg":3,"min":1,"max":4,"Count":8,"sCount":3,"sources":["x1","x2","x3","x4","x5","x6","x7","x8"]},{"timestamp":1424716980,"avg":2,"min":1,"max":3,"Count":4,"sCount":2,"sources":["x3","x4","x8","x4"]},{"timestamp":1424717160,"avg":2,"min":1,"max":3,"Count":9,"sCount":4,"sources":["x3","x4"]}]}}
The JSON data is invalid. If it is returned from a server, you need to go there and correct the data source, (if you have access to that).
Otherwise, perhaps notify the backend guy(s) about it.
If it is from a REST API, and you are "sure" that the server code should be error free, then check that you have supplied all the required parameters in the API request you are making.
I think your JSON is messed up. I ran it through JSONLint, and having the undefined at the beginning causes things to break.
I managed to get the JSON array into (look http://yrs2013.bugs3.com/mpapp/getSTORY.php?url=http%3A%2F%2Fcontent.guardianapis.com%2Fsearch%3Fq%3DJohn%20Stevenson%20mp%26page-size%3D3%26format%3Djson there for the array details), Javascript as a JS object - however now when i try and call a piece of data from the array it comes back as 'undefined'.. Any tips? :)
JS Code:
$.getJSON('getSTORY.php?url='+ url2, function(response)
console.log(response);
//logs the response, comes up as object in the log;
var e = response.status;
//when e is logged it just says 'undefined'
console.log(e);
In the log the object looks like drop down menus, which is different to my previous attempts of similar things as they came back from the PHP as text. I have tried JSON.parse but however that came back with the undefined o error! :l any help gratefully accepted! Thanks!
By looking at your JSON structure, I believe you need response.response.status. The first response is a variable holding your whole object, which contains a single response property with status inside (as well as results, etc).
I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.