简体   繁体   中英

AJAX within AJAX not working correctly

I am working on social site. On first load, it fetches all the post, each with two comment max. If the comments are more than two it attach More comment button to it, if clicked, it displays all the comments and replace the button with Less comment .

That is just a little story of how it works. I want whenever a comment is made, it should be appended to existing ones and displayed instantly via AJAX. It does this but it redisplay each comments 3 times, when you reload the page, everything is okay...

<div class = 'post_updates'>
  <div class = 'feeds'>
    <div class = 'commentdiv'>
       <textarea autocomplete = 'off' class='commenttext form-control' rows = '1'
       placeholder='Have your say...'></textarea>
       <button class='comment btn btn-xs btn-primary onespacedown' value = '7'
        type='submit'>Comment</button>
    </div>
  </div>
</div>

The jQuery AJAX code:

 $('.feeds').on('click', '.comment', function () {
var $this = $(this);
var post_comment = $this.parents('.feeds').find('.commenttext').val();
var post_id = $(this).val();
var user_id = $(".user_id").text();
var request = $.ajax({
      url: "insert.php",
      type: "POST",
      data: { post : post_id , user : user_id, comment: post_comment },
      dataType: "html"
    });
    request.done(function( msg ) {    
        $pc = $this.parents('.feeds').find('.per_comment');
        //fetch comments and display
            var request = $.ajax({
                url: "comments.php",
                type: "POST",
                data: {
                    post: post_id,
                    user: user_id
                },
                dataType: "html"
            });
            request.done(function (msg) {
                $pc.html(msg).data('loaded', true);
                $this.replaceWith("<button class='lesscomments btn-block pullcomments' value='' name = 'more' type='submit'>Less comments</button>"); 
                $this.parents('.feeds').find('.commenttext').val('');
        });
    });
})

In advance, thanks.

try $.post in jquery

$.post("insert.php",{post : post_id , user : user_id, comment: post_comment},function(){})
.success(function(data){
    //callback when first post completed
    //begin second ajax post
    $.post("comments.php",{post: post_id,user: user_id},function(){})
    .success(function(){
        //call back when second post completed
    });
});

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