Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 824
Eugene Shmorgun Avatar asked Dec 26 '22 18:12

Eugene Shmorgun


2 Answers

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.

like image 162
Florian Bauer Avatar answered Dec 29 '22 09:12

Florian Bauer


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

like image 21
Daniil Ryzhkov Avatar answered Dec 29 '22 08:12

Daniil Ryzhkov