Javascript array - element access - javascript

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?

Related

Ajax request pass data?

I want to send an array in Ajax data request, but I the output that I get display items[..], How to get rid of it, so I can only fetch variable inside it?
var columnName = 'accountLedgerID';
var gridDataArray = $('#grid').data('kendoGrid').dataSource.data();
var items = {
method: "updateSequence",
this_propertyID: $('#thisPropertyID').val(),
this_length: gridDataArray.length,
};
for ( var i=0; i < gridDataArray.length; i++ ) {
items["sequence_" + i] = i;
items["accLedgerID_" + i] = gridDataArray[i][columnName];
}
$.ajax({
url: "./getLedgerManagement.php",
type: "POST",
data: {
//items - display a same result as below
items:items
},
sucess: function(data){
console.log('success')
}
});
I expect it return data like this.
method: "updateSequence"
this_propertyID: "1"
this_length: 23
sequence_0: 0
accLedgerID_0: "LA26"
sequence_1: 1
accLedgerID_1: "LA8"
sequence_2: 2
accLedgerID_2: "LA29"
sequence_3: 3
accLedgerID_3: "LA2"
.....

get values from json object list

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']);
}
}
}
});

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 abort ajax request

In my below code if input search vale is empty and as well as search keyword is same means if entered 'abc' got the result again clicked need to abort the ajax request, I had written in beforesend method but browser throwing error "Cannot read property 'abort' of undefined"
Ajax code:
function makeRequest()
{
var searchText='';
var popupRequest = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
popupRequest.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
}
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
var xhr = null;
function makeRequest()
{
if( xhr != null ) {
xhr.abort();
xhr = null;
}
var searchText='';
xhr = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
xhr.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
Define a variable and give your ajax the same alias. Then, everytime the function is being made, you check if (in this example XHR) is null or not. If it is not, you abort() it and give it null value again.

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