0

The goal of this code is to make dinamical select input with option from database

$.ajax({
            url: "<?=site_url('purchase_order/getDataForPurchase')?>/" + $("#POID").val(),
            success: function(data){
                var xmlDoc = $.parseXML(data);
                var xml = $(xmlDoc);
                var display=[];
                var i=0;
                $("#selectedItems").html('');
                $.map(xml.find('orderItem').find('item'),function(val,k){
                    var idProduct = $(val).find('proi_product_id').text();
                    $("#selectedItems").append(
                        '<tr>'+
                            '<input type="hidden" id="idItem'+i+'" name="idItem'+i+'" value="'+idProduct+'>'+
                            '<td><select id="selItemUnit'+i+'" name="selItemUnit'+i+'"></select></td> '+
                        '</tr>'
                    );
                    $.ajax({
                        url: "<?=site_url('adjustment/getUnitsByProductID')?>/" + $("#idItem"+i).val()+"/0",
                        success: function(data1){
                            var xmlDoc1 = $.parseXML(data1);
                            var xml1 = $(xmlDoc1);
                            $.map(xml1.find('Unit').find('item'),function(val1,j){
                                var intID1 = $(val1).find('id').text();
                                var strUnit1=$(val1).find('unit_title').text();
                                $('#selItemUnit'+i).append('<option value="'+intID1+'">'+strUnit1+'</option>');
                            });
                        }
                    });                        
                    i++;
                });
            }
        });

the problem is that in the inner ajax, the value of i is always same. if the item is 2 than it always 2. Not 0,1.

go eng chun
  • 73
  • 2
  • 10
  • For starters, even though `.map()` iterates a collection, you're clearly miss-using it. The point of it is to return a modified version of each element in the collection. You're probably looking for `.each()` – Johan May 26 '14 at 19:06
  • 1
    Possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). `i` will have already been incremented *before* either `success:` callback is called, and they refer to the variable and its value at the moment rather than the value `i` had when the request started. – Jonathan Lonowski May 26 '14 at 19:06

0 Answers0