Eugene Shmorgun
Eugene Shmorgun

Reputation: 2075

Foreach-loop for Array, which got via AJAX-query

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: enter image description here

Upvotes: 4

Views: 47080

Answers (4)

sagar shrestha
sagar shrestha

Reputation: 5

Use $.each method of jQuery, not used foreach.

$.each(res.keyVar, function(index, row) {
   alert(row);
});

Upvotes: 0

Florian Bauer
Florian Bauer

Reputation: 636

If 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.

Upvotes: 6

Daniil Ryzhkov
Daniil Ryzhkov

Reputation: 7596

Javascript doesn't have foreach construction. Use $.each method of jQuery

Upvotes: 4

Lucas Green
Lucas Green

Reputation: 3959

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

});

Upvotes: 0

Related Questions