0

I have this messaging system (aka wall). It works to add new messages and If I want to cancel the messages loaded from the database. But if I want to cancel the new messages which have just been appended (without reload the page) it doesn't.

$("#wallButton").on("click",function(){

        var textdocument =  document.getElementById('input_post_wall').value
        var poster = '<?php echo escape($userLogged->data()->user_id);?>';
        var date = '<?php echo $humanize->humanize()->naturalDay(time());?>';
        var time = '<?php echo $humanize->humanize()->naturalTime(time());?>';
        var timeNow =  '<?php echo time();?>';


if(textdocument.length>0){

$.ajax({
      url: '/post_process.php',
      type: 'post',
      dataType: 'json',
      data: {'action': 'post', 'userid': userId, 'poster': poster, 'text':textdocument, 'time':timeNow},
      success: function(data) {
          var  LastID = data["postID"];
      var image = data["image"];
      var sex = data["sex"];
      var name = data["name"];


            if(image){

                      image = "/userImages/"+poster+"/"+poster+".jpg";
            }else{

                    if(sex == 'male'){
                              image = '/images/male_profile.png';

                    }if (sex == 'female'){

                              image = '/images/female_profile.png';

                    }
                  }

        $('.postDiv').prepend('<div class="post"  data-post-id= "'+LastID+'"><img src="'+image+'" class="postImg"><div class="formatted-text"><h4>'+name+'</h4><h5>'+textdocument+'</h5><h6>'+date+' - <span>'+time+'</span></h6><a style="font-size:10px;"class="cancelPost" data-cancel-id= "'+LastID+'">cancel</a></div></div>').hide().fadeIn('slow');
            textdocument.val('');

         },

    }); // end ajax call 


}else{

  alert('no text');

}

});//end click function 



 //this cancel post from wall but it only works for the messages displayed when the page has been     loaded. I will write the code to cancel the message from database when the jquery part works. 

    $('.cancelPost').each(function (e) {

    var $this = $(this);
    $this.on("click", function () {
        value = $(this).data('cancel-id');


    $('div[data-post-id="'+ value +'"]').fadeOut("slow", function(){ $(this).remove(); });


    });
});

this is the php function that fetches all the message from the database when page is loaded.

public function presentPost($userId){

    $query = $this->_db->prepare("SELECT * FROM wall WHERE user_ident = ? ORDER BY postId DESC");  
        if ($query->execute(array($userId))){
                $result = $query->fetchAll(PDO::FETCH_OBJ);
                    foreach ($result as $row) {

                $user =  New User($row->posterId);

                 if($user->data()->image == 0){

                     if($user->data()->sex == 'male'){
                      $image = '/images/male_profile.png';

                      }else{
                       $image = '/images/female_profile.png';

                      }

                 }else{

                     $image = "/userImages/$row->posterId/$row->posterId.jpg";

                 }  

 echo'<div class="post" data-post-id= "'.$row->postId.'"><img src="'.$image.'" class="postImg">    <div class="formatted-text"><h4>'.$user->data()->name.' '.$user->data()->lastName.'</h4><h5>'.$row->textPost.'</h5><h6>'.$this->_humanize->naturalDay($row->time).' - <span>'.$this->_humanize->naturalTime($row->time).'</span></h5><a style="font-size:10px;"class="cancelPost"  data-cancel-id= "'.$row->postId.'">cancel</a></div></div>';
                    }
            }
        }
Mat
  • 6,236
  • 9
  • 42
  • 55
  • possible duplicate of [jQuery - Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements) – Ram Mar 16 '14 at 06:39

1 Answers1

0

you should use delegates for that

$(document).on("click",".cancelPost", function () {
    value = $(this).data('cancel-id');


    $('div[data-post-id="'+value+'"]').fadeOut("slow");

    $('div[data-post-id="'+value+'"]').remove();

});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
  • You don't delegate the event. The second parameter of the `on` should be a selector. If you have access to the element, then delegation doesn't make any sense. – Ram Mar 16 '14 at 06:35
  • yes, the edited answer works great!... you guys are too quick to answer.... I have to wait 4 minutes to accept it. ;-) – Mat Mar 16 '14 at 06:39