I have the JS-code:
$("#select_bank").change(function () {
selected_bank = $("#select_bank option:selected").text();
$.ajax({
type: 'POST',
dataType: 'html',
data: {
selectedBank: selected_bank
},
url: '<?= base_url() . 'atm/select_region'; ?>',
success: function (list_regions) {
foreach(keyVar in list_regions) {
alert(list_regions[keyVar]);
}
}
});
});
On callback "succes"s I get the array from server's script - in alert I see the "Array" - so I want to iterate via this array on client-side like I coded above, but when doing I get the error in console - "var keyVar is not defined". As I understand I need to typecast the list_regions
param as array or some another way to fix it. Please, how to make it better?
Thanks!
upd:
I have the JS-code:
$("#select_bank").change(function () {
selected_bank = $("#select_bank option:selected").text();
$.ajax({
type: 'POST',
dataType: 'html',
data: {
selectedBank: selected_bank
},
url: '<?= base_url() . 'atm/select_region'; ?>',
success: function (list_regions) {
foreach(keyVar in list_regions) {
alert(list_regions[keyVar]);
}
}
});
});
On callback "succes"s I get the array from server's script - in alert I see the "Array" - so I want to iterate via this array on client-side like I coded above, but when doing I get the error in console - "var keyVar is not defined". As I understand I need to typecast the list_regions
param as array or some another way to fix it. Please, how to make it better?
Thanks!
upd:
Share Improve this question edited Sep 1, 2012 at 6:42 Eugene Shmorgun asked Sep 1, 2012 at 6:10 Eugene ShmorgunEugene Shmorgun 2,07512 gold badges42 silver badges69 bronze badges 1- 1 Try changing 'foreach' to 'for' – timidboy Commented Sep 1, 2012 at 6:15
4 Answers
Reset to default 6If I am right you cannot transform the foreach loop into jquery in that way.
You should use .each to iterate the values
$.each(list_regions, function(index, value) {
alert(value);
});
You can find more information here.
Javascript doesn't have foreach
construction. Use $.each
method of jQuery
Try this:
$("#select_bank").change(function(){
// The following line was missing a var declaration,
// Making it an implicit global
var selected_bank = $("#select_bank option:selected").text();
$.ajax({
type:'POST',
dataType:'html',
data: { selectedBank: selected_bank },
url:'<?=base_url().'atm/select_region'; ?>',
success:function(list_regions){
var keyVar;
for(keyVar in list_regions) {
if (list_regions.hasOwnProperty(keyVar)) {
alert(list_regions[keyVar]);
}
}
}
});
});
Use $.each
method of jQuery, not used foreach.
$.each(res.keyVar, function(index, row) {
alert(row);
});