I am trying to loop through a JSON array.
here is example output
{
"calls": [
[
{
"interactionId": "2002766591",
"account_id": "",
"mid": "",
"Eic_CallDirection": "O",
"Eic_RemoteAddress": "5462223378",
"Eic_LocalAddress": "1062",
"Eic_State": "I"
}
]
],
"status": [
{
"statusId": "Available",
"userId": "su",
"loggedIn": false
}
]
}
here is my jQuery code.
<script>
$(function(){
function isset(a, b){
if(typeof a !== "undefined" && a){
return a
}
return b;
}
setInterval(function() {
$.getJSON("showMEssages.php", {method: "getMessages"}, function(data){
if(data.calls.length == 0 || !data.calls){
console.log('No Messages');
}
var c;
$.each(data.calls, function(i, item){
c = item[i];
console.log(c);
var interactionId = isset(c.interactionId, 0);
var Eic_CallDirection = isset(c.Eic_CallDirection, '');
var Eic_State = isset(c.Eic_State, '');
var AccoRDI_mid = isset(c.AccoRDI_mid, '');
var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');
if( Eic_CallDirection == 'I' && Eic_State == 'A'){
console.log('Call From ' + Eic_RemoteAddress + ' MID: ' + AccoRDI_mid );
}
if(Eic_CallDirection == 'O' && Eic_State == 'C'){
console.log('Live Call With ' + Eic_RemoteAddress );
}
});
});
}, 1000);
});
</script>
my code is working but I get since it runs every second I keep getting this error in the logs
TypeError: c is undefined
and the error point to this line
console.log(c);
what is the cause of this issue and how can I correct it?
Nathan Dawson
19.4k3 gold badges59 silver badges60 bronze badges
asked May 14, 2015 at 0:43
-
your code works for me in my fiddle, unless your actual json is not the one you posted jsfiddle.net/etuLsedkEduardo Wada– Eduardo Wada2015年05月14日 01:34:54 +00:00Commented May 14, 2015 at 1:34
2 Answers 2
In this function:
$.each(data.calls, function(i, item){});
item
is the value of each element in data.calls
, so you don't need to use item[i]
. Just c = item
is enough.
answered May 14, 2015 at 0:51
-
1in his json, calls is an array of arrays, getting the ith element makes senseEduardo Wada– Eduardo Wada2015年05月14日 01:34:09 +00:00Commented May 14, 2015 at 1:34
-
i
is the index ofitem
indata.calls
Tuan Anh Hoang-Vu– Tuan Anh Hoang-Vu2015年05月14日 01:41:41 +00:00Commented May 14, 2015 at 1:41
I figured out the issue. I had to do a loop with in a loop since I have array with in array
$.each(data.calls, function(i, item){
$.each(item, function(z, c){
var interactionId = isset(c.interactionId, 0);
var Eic_CallDirection = isset(c.Eic_CallDirection, '');
var Eic_State = isset(c.Eic_State, '');
var AccoRDI_mid = isset(c.AccoRDI_mid, '');
var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');
if( Eic_CallDirection == 'I' && Eic_State == 'A'){
console.log('Call From ' + Eic_RemoteAddress + ' MID: ' + AccoRDI_mid );
}
if(Eic_CallDirection == 'O' && Eic_State == 'C'){
console.log('Live Call With ' + Eic_RemoteAddress );
}
});
});
answered May 14, 2015 at 1:49
lang-js