简体   繁体   中英

JQuery function not executing on document load

I am trying to build a simple social media website in which people get to make posts and comment on the postings (Kinda like facebook). In order to fetch the posts and the comments, I have created two simple PHP scripts that get me the results in a json format. I then created two functions in jquery, getPosts() and getComments() to ajax the results. On success, these functions clone() the html frame I have created for each post/comment object that is returned.

Here is my html frame:-

    <div class="KK-posts_feed">

            <div class="KK-post_frame" style="display:none;"> //This is the div that I clone() for postings

                <div class="KK-post_info_header">
                        <a class="KK-post_username"></a>    
                   </div>
                </div>

                <div class="KK-post_text"></div>

                <div class="KK-post_comment_thread" data-PID="">
                    <div class="KK-post_comment_box"> //This is the div that I clone for comments

                        <div class="KK-post_comment_user_info">
                            <a class="KK-post_comment_username"></a>
                        </div>
                        <div class="KK-post_comment_text"></div>
                    </div>
                </div>
            </div>
        </div>

This is the getPosts() method to output the posts:-

    function getPosts(){  //This function gets the posts and clones the html for each post
        $.ajax({
        type : 'GET',
        url : 'fetchposts.php',
        dataType: 'json',
        error : function(){
            $('.dash_results_bar').html('<p class="KK-post_load_error">' + "Sorry, couldn't load posts at the moment. This maybe because we are facing downtime or because the databases are being updated." + ' <a href="#" class="KK-post_load_retry">Retry</a>' + "</p>");
        },
        success : function(data)
        {
         var posts = data.posts;

            if(posts.length)
            {
                $('.KK-post_frame:first').css("display", "block");
                $(posts).each(function(index, value){
                    $('.KK-post_frame:first')
                    .clone(true)
                    .attr('id', (value.post_id))
                    .find('.KK-post_username').html(value.user_fullname)
                    .end()
                    .find('.KK-post_text').html(value.post_text)
                    .end()
                    .find('.KK-post_comment_thread').attr('data-PID', value.post_id)
                    .end()
                    .appendTo('.KK-posts_feed');
                });
                $('.KK-post_frame:first').css("display", "none");
            }
        }   
    });
}

This is the getComments() method to output the comments under each post:-

function getComments(){
        $('.KK-post_comment_thread').each(function(){ // I run this method for each comment thread div inside each of my posts div
        var pid = $(this).attr('data-PID'); // PID is the 'post id' that I use, to identify each comment thread div separately.
        var self = this;
        $.ajax({
            type : 'POST',
            url : 'fetchcomments.php',
            data : 'pid='+pid, // I send the post id to the php script which returns the comments for the particular post in the form of json objects
            error : function(){
                $(self).html('<p class="KK-post_comment_load_error">' + "Sorry, couldn't load comments at the moment." + ' <a class="KK-post_comment_load_retry" href="#">Retry</a>' + "</p>");
            },
            success : function(data){
                var comments = data.comments;

                if(comments.length)
                {
                    $('.KK-post_comment_box:first').css('display', 'block');
                    $(comments).each(function(index, value){
                        $('.KK-post_comment_box:first')
                        .clone(true)
                        .attr('id', value.comment_id)
                        .find('.KK-post_comment_username').html(value.user_fullname)
                        .end()
                        .find('.KK-post_comment_text').html(value.comment_text)
                        .end()
                        .appendTo(self);
                    });
                    $('.KK-post_comment_box:first').css('display', 'none');
                }
            }   
        });

    });
}

This is how I execute the above two functions :-

$('document').ready(function(){

     $.when(getPosts()).done(function(){

          getComments();
     });

});

While the getPosts() method executes perfectly and outputs the posts, the getComments() method either doesn't execute or doesn't show any results. I cant say for sure because everytime I refresh the page, I only get the postings and not the comments. Also I checked my console but did not find any errors with the script. The getComments() method worked perfectly well when I executed it via the click event handler like $('button').click(function(){ getComments(); }); . Therefore, I know that both my methods are working fine, its just that I am not able to execute them one after the other on page load. Can anybody help me with this peculiar problem?

Your getPosts() function doesn't return anything, so you're passing undefined to $.when() .

You need to return what's returned from $.ajax() :

function getPosts(){  //This function gets the posts and clones the html for each post
    return $.ajax({
      // ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM