I am pulling in data through ajax to populate a facebook-like wall type application (or a twitter wall).
But I’m getting undefined when i try to access the first li- if anyone can spot my obvious mistake it would be appreciated
var get_venues = function(){
$.ajax({
type: "GET",
url: '<?=base_url()?>wall/start_to_grab/',
dataType: "JSON",
success: function(data) {
var sel = $("#wall");
sel.empty();
for (var i=0; i < data.length; i++) {
sel.append('<li id="'+data[i].post_id +'"> ' + data[i].title + '</li>');
}
}
});
//start_poll($('ul#wall li:first').attr('id'));
alert($("ul#wall li:first").attr("id")); // returns undefined
};
The code returns undefined even when i can see the element on the page.
That is the way AJAX works (asynchronously, as the name suggests). The
alertis executed before the AJAX request has returned a response, so nolielements have been appended.Move the
alertinside the AJAX success event handler. Alternatively, you could make the AJAX request synchronous, but that’s almost always not what you want.