0

I have the following code:

let html = '<h2 class="text-center">Опции</h2>'
     html += '<div class="col-md-4 col-md-offset-4">'
        html += '<div class="form-group">'
           html += '<select name="options" id="options-select" class="form-control">'
              html += '<option value="">-- Изберете опция --</option>'
                 //for loop for options
                 for(product_option of data.options) {
                    for(product_option_value of product_option.product_option_value) {
                        $.ajax({
                            url: '<?= $get_option_link ?>&token=<?= $token ?>',
                            type: 'POST',
                            data: {option_value_id: product_option_value.option_value_id}
                        })
                        .done(function(option) {
                            option = JSON.parse(option)
                            console.log(product_option.name + ' - ' + option.name)
                            html += '<option value="'+product_option_value.product_option_value_id+'">'+ product_option.name + ' - ' + option.name +'</option>'
                        })
                        .fail(function() {
                            console.log("error")
                        })
                        .always(function() {
                            console.log("complete")
                        })
                    }
                }
            html += '</select>'
        html += '</div>'
    html += '</div>'

    $('#products').val('')

    if (data.options.length > 0) {
        $('#product-options').append(html)
    }

and it appends everything fine except for the html in the for loop. I console logged the obbjest to check them they are all fine even the console.log right before the html += '<option...' part is working fine so I am sure the code in the loop is processed.

EDIT: plus there are no errors in the console in the inspector

Angel Miladinov
  • 1,596
  • 4
  • 20
  • 43

1 Answers1

1

That is because your calling Ajax asynchronous function, that means that will execute at a later time... after your loop has finished and the html variable is already set....

Try changing your ajax like this...

 $.ajax({
                        url: '<?= $get_option_link ?>&token=<?= $token ?>',
                        type: 'POST',
                        data: {option_value_id: product_option_value.option_value_id}
                    })
                    .done(function(option) {
                        option = JSON.parse(option)
                        console.log(product_option.name + ' - ' + option.name)
                        $('#options-select').append('<option value="'+product_option_value.product_option_value_id+'">'+ product_option.name + ' - ' + option.name +'</option>');
                    })
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37