Tuesday 13 June 2017

javascript - Data available only after alert











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 += '';
});
}
});
var l = parseInt($('.items .item').length);
var h = '
Item ' + (l + 1) + '
';



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


Answer



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 += '';
});

var l = parseInt($('.items .item').length);
var h = '
Item ' + (l + 1) + '
';
}
});



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...