2
    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.

1 Answer 1

2

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
});     
Sign up to request clarification or add additional context in comments.

2 Comments

OK. What should I use instead? Can you provide an example?
You should use the html variable only inside the success callback of your AJAX request, not outside it. That simply stems from the very nature of how AJAX works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.