get values from json object list - javascript

I have this json format.
{
"cod":"200",
"message":0.0027,
"cnt":40,
"list":[
{
"dt":1510045200,
"main":{
"temp":281.46
}
},
{
"dt":....
....
}
]
}
Using javascript and ajax request, I am trying to get the value of dt and temp from each object in data.list but with no result..
$.ajax({
url: "",
type: "GET",
success: function (data) {
//number of objects in data.list array
var numOfObjects = data.list.length;
for (var i = 0; i < numOfObjects; i++){
if(data.list[i].hasOwnProperty('td')){
console.log(data.list[i].['td']);
}
else if(data.list[i].['main'].hasOwnProperty('temp')){
console.log(data.list[i].['main'].['temp']);
}
}
}
});

You don't need to put a . between array keys :
For example : data.list[i].['dt'] is incorrect, data.list[i]['dt'] is correct.
$.ajax({
url: "",
type: "GET",
success: function (data) {
//number of objects in data.list array
var numOfObjects = data.list.length;
for (var i = 0; i < numOfObjects; i++){
if(data.list[i].hasOwnProperty('dt')){
console.log(data.list[i]['dt']);
}
else if(data.list[i]['main'].hasOwnProperty('temp')){
console.log(data.list[i]['main']['temp']);
}
}
}
});

Related

Javascript array - element access

I have
var prosjeci = [];
var parametar = $("#parametar1").val();
Function for getting data from server:
function podatciPrethodniDan()
{
$.ajax({
type: "POST",
url: "php/getPreviousDayData.php",
dataType: "json",
data: {parametar: parametar },
success: function(data)
{
obradiPodatkePrehtodnogDana(data);
}//end of success
});//end of ajax
}
Function which fill array with data:
function obradiPodatkePrehtodnogDana(data)
{
var stanica1Prosjek = 0;
var stanica2Prosjek = 0;
var stanica3Prosjek = 0;
var stanica4Prosjek = 0;
console.log(data);
for(i=0; i<data.length; i++)
{
if(i<24)
{
stanica1Prosjek = stanica1Prosjek + parseFloat(data[i].par);
}
else if(i>=24 && i<48)
{
stanica2Prosjek += parseFloat(data[i].par);
}
else if(i>=48 && i<72)
{
stanica3Prosjek += parseFloat(data[i].par);
}
else
{
stanica4Prosjek += parseFloat(data[i].par);
}
}
prosjeci.push(stanica1Prosjek/24);
prosjeci.push(stanica2Prosjek/24);
prosjeci.push(stanica3Prosjek/24);
prosjeci.push(stanica4Prosjek/24);
}
Results of console.log(data):
(only first elment)
Array[96]
0:Object
datum:"2016-10-31"
par:"60"
stanica"1"
Call function
podatciPrethodniDan();
Print out array:
console.log(prosjeci);
console.log(prosjeci[0]);
I get all data succesfull and i fill array sucessfull but i can't to access array element.
Results of first console.log:
Array[4]
0:60.44999999999999
1:76.41666666666667
2:85.3875
3:82.47083333333335
length:4
Results of second console.log:
undefined
I cant access arrays element?

Getting type error while using Ajax call in JavaScript/jQuery [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I am getting the following error while extracting some value inside loop using jQuery. I am showing my error below.
Uncaught TypeError: Cannot read property 'no_of_optional' of undefined
I am providing my code below.
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i != 0) {
$("#questions0").val(qdata[0].questions);
$('#noofoption0').val(qdata[0].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[0]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
for (var j = 0; j < qdata[0].no_of_optional; j++) {
}
}
cnt++;
}
})
}
if (i == 1) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
}
}
})
I am getting error at this console.log('first question',qdata[i].no_of_optional); .Actually qdata is containing the two set of data(qdata[0],qdata[1]) but inside the second ajax call i is becoming 2.
Here I am expecting qdata[1].no_of_optiona inside second ajax call.
use a closure, by the time the done callback is called the for loop has finished and incremented i:-
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i == 1) {
(function(i) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
})(i);
}
}
})

How to get JSON result from an API call using jQuery(or Javascript) in a non-Ajax way?

I am new to JS an jQuery. And I am trying to build a key-value map from an API call which returns an array of key-value pairs.
[{"key":"191","value":244}, ... , {"key":"920","value":130}]
I came up with this ajax code. But following code will need the map constructed from loadMap. How to change it to non-ajax way that the "followingFunction" runs after loadMap finishes>
var mp = {};
(function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
}
});
}());
//followingFunction which needs the information from mp
You can solve this in two different ways.
1) ExecutefollowingFunctionat the end of your success callback:
var mp = {};
function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
followingFunction();
}
});
};
loadMap();
2) Set the async flag to false (by default this flag is true). This will result in blocking call with synchronous execution:
var mp = {};
function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
async: false,
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
}
});
};
loadMap();
followingFunction();

javascript wait for several callback finished

I have a following javascript program:
function jQueryFunction(url, callback)
{
$.ajax
({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
return callback(json);
}
});
}
var jsonArray = new Array();
for(var i = 0; i < 10; i++)
{
jQueryFunction(url[i], function(json){
jsonArray[i] = json;
});
}
//process jsonArray
However, when I check jsonArray after the for loop, it is null. So my question is that how to store the return value from jQueryFunction to jsonArray in for loop and then process it?
I have tried $.when.apply($,jsonArray).done(function) but still the same, it is null.
A simple way:
function doTheAjax(url, callback) {
return $.ajax({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler"
});
};
var reqs = [];
for(var i = 0; i < 10; i++) {
reqs.push(doTheAjax(url[i]));
}
// send the array of requests to when, which will fire `done`
// when it's, well, done
$.when.apply($.when, reqs).done(function() {
$.each(arguments, function(data) {
// process the data
});
});
alternatively, make a bunch of requests and put them into jsonArray, but keep
track of how many you're making. When they all complete, you have the array. Create your
own deferred, resolve it yourself when the counter is up, and return the promise.
var getJSON = function(url) {
var dfd = $.Deferred();
var count = 0;
var total = 10;
var jsonArray = [];
for(var i = 0; i < total; i++) {
doTheAjax(url[i]).done(function(json) {
jsonArray.push(json);
count++;
if ( count >= total ) {
dfd.resolve(jsonArray);
}
});
}
return dfd.promise();
};
getJSON().done(function(theCreatedJsonArray) {
// do stuff
});
I'm not sure why the answer to your previous question (using deferreds) didn't work. But the cause of your problem is that you are checking the array before any of the ajax responses arrived. You also have a problem with i referencing the same value on all callbacks.
One simple workaround, if you know how many responses you're expecting:
var arr = [];
for(var i = 0; i < 10; i++){
jQueryFunction(url[i], function(json){
arr.push(json);
if(arr.length == 10) {
// All 10 responses arrived!
// DO STUFF FROM HERE
// e.g., call another function
console.log(arr);
}
});
}

Send back returned response to ajax call

I have a ajax function in index.php which calls on the page thread.php which returns a JSON response(array). I basically want to parse through that array, display it in a particular html format, take the last value of the last row of that array and send it back in the same ajax call previously mentioned. So that ajax is basically a loop.
function returnValue()
{
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
var dateposted = results[5];
}
}
}
}
});
}
The stored value dateposted needs to be sent as an input when making the ajax call. The default value of dateposted will be 0.
I am not sure if this can be done. I am open to suggestions.
You can make this a lot simpler, you don't need to use the extended GET syntax:
var returnValue = (function() {
var dateposted = 0;
return function() {
$.get("thread.php", { "lastposted": dateposted }, function(result) {
// display your chats
dateposted = result[result.length-1][5];
}, "json");
}
})();
One simple way to your problem is declaring dateposted with a default value outside the function call and use it in the loop to store to store the last value. And have a new Ajax function call. I hope this is want you want.
function returnValue()
{
var dateposted=0;
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
dateposted = results[5];
}
}
}
}
});
}

Categories

Resources