somejkuser
somejkuser

Reputation: 9040

jquery html not passing back to html variable within getJSON function scope issue

    html += '<ul>';
    var url = '/jr/public/ajax/stories.php?storyId=' + data.storyId + '&type=comments' ;        
    jQuery.getJSON(url,function(datum){                     
        jQuery.each(datum,function(i,elm){
            html += '<li><div class="c-thumb">';
            html += '<img alt="" src="'+elm.thumbImageUrl+'"/>';
            html += '<div class="c-text">';
            html += '<h6><a href="">'+elm.userName+'</a> - '+elm.dateStamp+'</h6>';
            html += '<p>' + elm.commentContent+'</p>';
            html += '</div></li>';      
        });
    });     
    html += '</ul>';

The html variable is not adding the content from the getJSON function to the html variable set outside the scope.

Upvotes: 2

Views: 134

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

The getJSON function returns immediately. That's because the first A letter from the AJAX acronym means asynchronous. The request is sent and when the server completes the processing, the callback gets executed.

So, it is only inside this callback that you can use the html variable.

var url = '/jr/public/ajax/stories.php';
jQuery.getJSON(url, { storyId: data.storyId, type: 'comments' }, function(datum) {                     
    var html = '<ul>';
    jQuery.each(datum,function(i,elm){
        html += '<li><div class="c-thumb">';
        html += '<img alt="" src="'+elm.thumbImageUrl+'"/>';
        html += '<div class="c-text">';
        html += '<h6><a href="">'+elm.userName+'</a> - '+elm.dateStamp+'</h6>';
        html += '<p>' + elm.commentContent+'</p>';
        html += '</div></li>';      
    });

    html += '</ul>';
    // Here and only here use the html variable. For example you could update the
    // DOM with the value of this variable
});     

Upvotes: 2

Related Questions