4

Possible Duplicate:
jQuery: Return data after ajax call success

I wrote a script which adds a new div container to the said with the a select field inside. The data for the select field is loaded with an ajax request before. But for some reason the fields are only visible when I output something with alert().

var o = '';
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: webroot + 'items',
                success: function(data) {
                    $.each(data, function(index, value) {
                        o += '<option value="' + index + '">' + value + '</option>';
                    });
                }
            });
            var l = parseInt($('.items .item').length);
            var h = '<div class="item"><span class="bold">Item ' + (l + 1) + '</span><select id="ItemName" name="data[Item][name]">' + o + '</select></div>';

I have actually no idea how to solve this problem. Can you help me?

Community
  • 1
  • 1
Fortuna
  • 611
  • 6
  • 18
  • Code sample provided is not enough to figure out how you are trying to achieve the task. Provide a more elaborate one, or setup a test one on jsfiddle.net – bPratik Mar 12 '12 at 01:47

1 Answers1

5

Ajax is asynchronous. Move all of your code into the success function, and it will work. The reason it works with alert is because the alert allows some time to get the AJAX result.

$.ajax({
    type: 'post',
    dataType: 'json',
    url: webroot + 'items',
    success: function(data) {
        var o = '';
        $.each(data, function(index, value) {
            o += '<option value="' + index + '">' + value + '</option>';
        });

        var l = parseInt($('.items .item').length);
        var h = '<div class="item"><span class="bold">Item ' + (l + 1) + '</span><select id="ItemName" name="data[Item][name]">' + o + '</select></div>';
    }
});

Your code doesn't actually do anything other than load some html into a variable though. So whatever you were doing with "h", do it in the success function.

GoldenNewby
  • 4,382
  • 8
  • 33
  • 44