Jump to content
shan2batman

dynamically loaded events are not working properly

Recommended Posts

hi, guys i managed to load contents from database dynamically using ajax (JQUERY) but the problem is i'm not able to make them work properly, as i have jquery events to hide classes that are not hiding and links that wont do their normal behaviour when clicked. dont know where i'm going wrong. Any help would be appreciated. 

 

here is the jquery code that loads data dynamically:

//logic for infinite scroll
  
                var load=0;
     
     var sess_uname="<?php echo $session_uname;?>";
     var f_uname="<?php echo $f_uname;?>";
     var sess_count="<?php echo $total_sess_count;?>";
     var f_count="<?php echo $total_friend_count;?>";
     if(sess_uname==f_uname){
         $(window).scroll(function(){
             if($(window).scrollTop()==$(document).height()-$(window).height()){
             load++;
       
             if(load *2 >sess_count){
                 $(".message").text("no more posts to show");
             }else{
                 $.post("st&com.php", {load:load},function(data){
                  $("#status_area").append(data);
                    
                 });
             }
             }
         });
     }   

here is the code for dynamically loaded elements in php:

<?php

include "includes/dbconfig.inc.php";
$status_replies="";
$status_list="";
$statusui_edit="";
$isowner="";
$is_friend="";
$statusdeletebutton='';     
$reply_delete_button="";
$load=  (int)($_POST['load'])*2;
function hashtags($dat) {
$regex="/#+([a-zA-z0-9._-]+)/";
$dat1=  preg_replace($regex, '<a href="hash_sys.php?tag=$1">$0</a>', $dat);
return $dat1;
    
}
function taggingsys($dat) {
$regex="/@+([a-zA-z0-9!._-]+)/";

$dat1=  preg_replace($regex, '<a href="home.php?u=$1">$0</a>', $dat);
return $dat1;
    
}
$sess_id=(int)$_SESSION['id'];
$friends = array();
$stmt=  $conn->prepare("select friend_one, friend_two from friends where (friend_one=:session OR friend_two=:session) and accepted='1'");
$stmt->bindparam(":session",$_SESSION['uname']);
$stmt->execute();
$fetch=$stmt->fetchAll();
$count=count($fetch);


    if($count==0){
     $totalids=$project->totalUpdates1($sess_id,$load); 
    
 /*   foreach ($totalids as $v) {
        print_r($v); 
    $id=$v['user_id'];
    //fetch update_id from update table in db and inject it to the feed query.
    //$totalUpdates=$project->totalUpdates1($id);   
   */ 
    foreach ($totalids as $row1){
   
                $updateid=$row1['update_id'];
            
                $account_name=$row1['account_name'];
                $u_id=$row1['user_id_u'];
                $author=$row1['author'];
                $post_date=$row1['time'];
                $title= stripslashes($row1['title']);
                $data= stripslashes($row1['update_body']);
             $data1=  hashtags($data);
           //   $data1=  taggingsys($data0);
              $pic=$project->viewByUname($author);
              $uid=$pic['user_id'];
         $datemade = strftime("%B %d", strtotime($post_date));
           $avatar=$pic['avatar'];
          if ($avatar!=""){
          $feed_pic='user/'.$uid.'/'.$avatar;
      }  else {
          $feed_pic='img/avatardefault.png';
          }
            
                include 'ratings/vote_count.php';
             $like='<a  type="like" class="btn status_like_'.$updateid.' like" attr="'.$updateid.'">Like</a>('.$num_likes[0].')';
             $unlike='<a  type="unlike" class="btn status_unlike_'.$updateid.' unlike" attr="'.$updateid.'">Dislike</a>('.$num_unlikes[0].')';
$share_button="";
                 $hidden_text= '<textarea class="hidden_textarea hidden_value'.$updateid.'" type="hidden" disabled>'.$data1.'</textarea>';
                   $share_button="<a class='btn share_btn share_".$updateid."' title='".$title."' type='share' id='".$updateid."'>Share</a>";
                   
             
                if ($author==$_SESSION['uname'] || $account_name==$_SESSION['uname']) {
                $statusdeletebutton='<li>'
                           . '<a  type="'.$updateid.'" class="btn delete_4_session hidden_text_delete_'.$updateid.' glyphicon glyphicon-trash delete_status_btn" title="Delete this status and its replies">Remove</a></li>';
                $edit_btn='<li>'
                        . '<a attr="'.$updateid.'" type="'.$updateid.'" class="btn edit_4_session hidden_text_edit glyphicon glyphicon-pencil" title="Edit this status" >Edit</a></li>';
                $statusui_edit="<div type='".$updateid."' class='hidden_edit_4_session session_editor".$updateid." jumbotron'>"
            . "<a type='".$updateid."' class='btn pull-right close_edit' title='Close without editing'>Close X</a>"
            . "<input type='text' class='form-control title_s_edit title_s_".$updateid."' name='status_title' value='".html_entity_decode($title)."' placeholder='Title' >"
            . "<span> </span>"
            . "<textarea id='wall_edit_1' type='".$updateid."' rows='5' cols='50'  class='session_edit text_value_".$updateid."' wrap='hard' placeholder='whats up ".$session_uname."'>
             ".html_entity_decode($data1)."</textarea><br>"
            . "<button style='float:right;' value='".$updateid."' type='a' class='btn btn-warning btn btn-large btn-lg post-s-edit'>Update</button></div>" ;
 
                }else{
                    $statusdeletebutton="";
                    $edit_btn="<li class='posted'>You are not the owner of this Post</li>";
                    $statusui_edit="";
                }
           
       echo $statusui_edit.''. $hidden_text.'<div attr="'.$updateid.'" type="'.$updateid.'" class="statusboxes status_'.$updateid.'  jumbotron">'
                        . '<h3 class="pull-left title">'
                        . '<div id="'.$updateid.'" class="title_s_2copy posted" value="'.html_entity_decode($title).'">'.html_entity_decode($title).'</div></h3>'
                        . '<span class="pull-right">'
                        . '<div class="dropdown">'
                        . '<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown"  >'
                        . '<span class="glyphicon glyphicon-edit"></span></button>'
                        . '<ul class="dropdown-menu">'
                         .$edit_btn .' '. $statusdeletebutton .'</ul></div></span><br><hr>'
                        . '<legend><span style="font-size: 13.5px;" class=" data_s_2copy" type="'.$updateid.'" >'
                        . html_entity_decode($data1).'</span></legend><b class="posted"><small>Posted by:-  <a href="home.php?u='.$author.'"><img src="'.$feed_pic.'" height="20px" width="20px"> '.$author.   '</a>   '.$datemade.'</small></b>'
                        . '<br><legend>'.$like.' | '.$unlike. ' | '.$share_button.'<h4><a id="'.$updateid.'" class="btn collap-btn">Comments</a></h4></legend>';
                       
       ?>

    <!-- Collapsible Element HTML -->
  
   <?php
// Fetch Comments of update
  echo '<div id="toggle'.$updateid.'" class="collapse">'; 
   $totalComments=$project->totalComments($_SESSION['uname'],$friend,$updateid);   
        foreach($totalComments as $row1){
             $status_reply_id=$row1['comment_id'];
                $reply_d=htmlentities($row1['comment_body']);
                $reply_data=  stripslashes($reply_d);
                $reply_osid=$row1['os_id'];
                $reply_date=$row1['time_c'];
                $reply_author=$row1['author_c'];
               $reply_data1=  hashtags($reply_data);
               // $reply_data1=  taggingsys($reply_data0);
                $datemade_r = strftime("%B %d", strtotime($reply_date));
                include 'ratings/vote_count4comments.php';
               $like_r='<a  type="like" class="btn status_liker_'.$status_reply_id.' like_r" attr="'.$status_reply_id.'">Like</a>('.$num_likes_r.')';
             $unlike_r='<a  type="unlike" class="btn status_unliker_'.$status_reply_id.' unlike_r" attr="'.$status_reply_id.'">Dislike</a>('.$num_unlikes_r.')';
      $pic=$project->viewByUname($reply_author);
              $uid=$pic['user_id'];
         
           $avatar=$pic['avatar'];
          if ($avatar!=""){
          $feed_r_pic='user/'.$uid.'/'.$avatar;
      }  else {
          $feed_r_pic='img/avatardefault.png';
          }
               
                 
        if ($reply_author==$_SESSION['uname'] ) {
                   $reply_delete_button='<li><a type="'.$status_reply_id.'" class="btn delete_reply_btn glyphicon glyphicon-trash delete_reply_"'.$status_reply_id.'" title="Delete this comment"> Remove</a></span></li>';
               } else{
                   $reply_delete_button="";
               }
              echo '
                <div  class="replyboxes pull-left reply_' .$status_reply_id.'">'
                      . 'Reply by:- '
                      . '<a href="home.php?u='.$reply_author. '"><img src="'.$feed_r_pic.'" height="20px" width="20px">'.$reply_author.'</a>'
                      . '<span class="pull-right">'.$datemade_r 
                       . '<b class="dropdown">
                         <small><span class="btn btn-xs btn-danger dropdown-toggle pull-right" data-toggle="dropdown"  >
                         <span class="glyphicon glyphicon-edit"></span></span>
                        <ul class="dropdown-menu">'.$reply_delete_button
                      . '</ul></span>'
                      . '</small></b><br><legend>'.  html_entity_decode($reply_data1).'<br>'.$like_r.'|'.$unlike_r.'</legend></div>';
               
              
               } 
        echo '<textarea id="reply_textarea_'.$updateid.'"  class="status_reply_'.$updateid.' input-custom2" placeholder="comment\'s"></textarea>'
                            . '<button id="reply_butn_'.$updateid.'" attr="'.$updateid.'" type="b" class="btn btn-warning pull-right btn-sm reply_butn reply_'.$updateid.'">Reply</button></div></div>';
                                
        }
} //}
else{
  $friends = array();
$stmt=  $conn->prepare("select friend_one, friend_two from friends where (friend_one=:session OR friend_two=:session) and accepted='1'");
$stmt->bindparam(":session",$_SESSION['uname']);
$stmt->execute();

   foreach ($stmt->fetchAll() as $i=> $r ) {
  
    $r["friend_one"] == $_SESSION['uname'] ? $friends[]= $r["friend_two"] : $friends[] = $r["friend_one"]; 
    
    $friend=$friends[$i];
    
    $friend_count=count($friends);
   
   
     $totalids=$project->totalids($_SESSION['uname'],$friend);  
   
     foreach ($totalids as $v) {
     
    $id=$v['user_id'];
   
    //fetch user_id from update table in db and inject it to the feed query.
    $totalUpdates=$project->totalUpdates1($id,$load);   
    $total_sess_count=$project->totalupdatescount($id);
   
    foreach ($totalUpdates as $j=>$row1){
   
                $updateid=$row1['update_id'];
                
                $account_name=$row1['account_name'];
                $u_id=$row1['user_id_u'];
                $author=$row1['author'];
                $post_date=$row1['time'];
                $title= stripslashes($row1['title']);
                $data= stripslashes($row1['update_body']);
              $data1=  hashtags($data);
              //$data1=  taggingsys($data0);
              $pic=$project->viewByUname($author);
              $uid=$pic['user_id'];
         $datemade = strftime("%B %d", strtotime($post_date));
           $avatar=$pic['avatar'];
          if ($avatar!=""){
          $feed_pic='user/'.$uid.'/'.$avatar;
      }  else {
          $feed_pic='img/avatardefault.png';
          }
                include 'ratings/vote_count.php';
             $like='<a  type="like" class="btn status_like_'.$updateid.' like" attr="'.$updateid.'">Like</a>('.$num_likes[0].')';
             $unlike='<a  type="unlike" class="btn status_unlike_'.$updateid.' unlike" attr="'.$updateid.'">Dislike</a>('.$num_unlikes[0].')';
$share_button="";
                 
                  $hidden_text= '<textarea class="hidden_textarea hidden_value'.$updateid.'" disabled>'.$data.'</textarea>';
                   $share_button="<a class='btn share_btn share_".$updateid."' title='".$title."' type='share' id='".$updateid."'>Share</a>";
                     
             
                if ($author==$_SESSION['uname'] || $account_name==$_SESSION['uname']) {
                $statusdeletebutton='<li>'
                           . '<a type="'.$updateid.'" class="btn delete_4_session hidden_text_delete_'.$updateid.' glyphicon glyphicon-trash delete_status_btn" title="Delete this status and its replies">Remove</a></li>';
                $edit_btn='<li>'
                        . '<a attr="'.$updateid.'" type="'.$updateid.'" class="btn edit_4_session hidden_text_edit glyphicon glyphicon-pencil" title="Edit this status" >Edit</a></li>';
                $statusui_edit="<div type='".$updateid."' class='hidden_edit_4_session session_editor".$updateid." jumbotron'>"
            . "<a type='".$updateid."' class='btn pull-right close_edit' title='Close without editing'>Close X</a>"
            . "<input type='text' class='form-control title_s_edit title_s_".$updateid."' name='status_title' value='".html_entity_decode($title)."' placeholder='Title' >"
            . "<span> </span>"
            . "<textarea id='wall_edit_1' type='".$updateid."' rows='5' cols='50'  class='session_edit text_value_".$updateid."' wrap='hard' placeholder='whats up ".$_SESSION['uname']."'>
             ".html_entity_decode($data1)."</textarea><br>"
            . "<button style='float:right;' value='".$updateid."' type='a' class='btn btn-warning btn btn-large btn-lg post-s-edit'>Update</button></div>" ;
 
                }else{
                    $statusdeletebutton="";
                    $edit_btn="<li class='posted'>You are not the owner of this Post</li>";
                    $statusui_edit="";
                }
           
       echo $statusui_edit.''. $hidden_text.'<div attr="'.$updateid.'" type="'.$updateid.'" class="statusboxes status_'.$updateid.'  jumbotron">'
                        . '<h3 class="pull-left title">'
                        . '<div id="'.$updateid.'" class="title_s_2copy posted" value="'.html_entity_decode($title).'">'.html_entity_decode($title).'</div></h3>'
                        . '<span class="pull-right">'
                        . '<div class="dropdown">'
                        . '<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown"  >'
                        . '<span class="glyphicon glyphicon-edit"></span></button>'
                        . '<ul class="dropdown-menu">'
                         .$edit_btn .' '. $statusdeletebutton .'</ul></div></span><br><hr>'
                        . '<legend><span style="font-size: 13.5px;" class=" data_s_2copy" type="'.$updateid.'" >'
                        . html_entity_decode($data1).'</span></legend><b class="posted"><small>Posted by:-  <a href="home.php?u='.$author.'"><img src="'.$feed_pic.'" height="20px" width="20px"> '.$author.   '</a> on   '.$datemade.'</b>'
                        . '<br><legend>'.$like.' | '.$unlike. ' | '.$share_button.'</legend></small>';
                       
       ?>
<h4><a id="<?php echo $updateid;?>" class="btn collap-btn">Comments</a></h4>
    <!-- Collapsible Element HTML -->
  <div id="toggle<?php echo $updateid;?>" class="collapse scroll-comments">
     
   <?php
// Fetch Comments of update
        $totalComments=$project->totalComments($_SESSION['uname'],$friend,$updateid);   
        foreach($totalComments as $row1){
             $status_reply_id=$row1['comment_id'];
                $reply_d=htmlentities($row1['comment_body']);
                $reply_data=  stripslashes($reply_d);
                $reply_osid=$row1['os_id'];
                $reply_date=$row1['time_c'];
                $reply_author=$row1['author_c'];
                $reply_data1=  hashtags($reply_data);
                //$reply_data1=  taggingsys($reply_data0);
                $datemade_r = strftime("%B %d", strtotime($reply_date));
                include 'ratings/vote_count4comments.php';
               $like_r='<a  type="like" class="btn status_liker_'.$status_reply_id.' like_r" attr="'.$status_reply_id.'">Like</a>('.$num_likes_r[0].')';
             $unlike_r='<a  type="unlike" class="btn status_unliker_'.$status_reply_id.' unlike_r" attr="'.$status_reply_id.'">Dislike</a>('.$num_unlikes_r[0].')';
      $pic=$project->viewByUname($reply_author);
              $uid=$pic['user_id'];
         
           $avatar=$pic['avatar'];
          if ($avatar!=""){
          $feed_r_pic='user/'.$uid.'/'.$avatar;
      }  else {
          $feed_r_pic='img/avatardefault.png';
          }
                 
        if ($reply_author==$_SESSION['uname'] ) {
                   $reply_delete_button='<li><a type="'.$status_reply_id.'" class="btn delete_reply_btn glyphicon glyphicon-trash delete_reply_"'.$status_reply_id.'" title="Delete this comment"> Remove</a></span></li>';
               } else{
                   $reply_delete_button="";
               }
              echo '
                <div  class="replyboxes pull-left reply_' .$status_reply_id.'">'
                      . 'Reply by:- '
                      . '<a href="home.php?u='.$reply_author. '"><img src="'.$feed_r_pic.'" height="20px" width="20px"> '.$reply_author.'</a>'
                      . '<span class="pull-right">'.$datemade_r 
                       . '<b class="dropdown">
                         <small><span class="btn btn-xs btn-danger dropdown-toggle pull-right" data-toggle="dropdown"  >
                         <span class="glyphicon glyphicon-edit"></span></span>
                        <ul class="dropdown-menu">'.$reply_delete_button
                      . '<li><a class="glyphicon glyphicon-warning-sign" href="report.php?u='.$reply_author.'"> Report</a><li></ul></span>'
                      . '</small></b><br><legend>'.  html_entity_decode($reply_data1).'<br>'.$like_r.'|'.$unlike_r.'</legend></div>';
               
              
               } 
        echo '<textarea id="reply_textarea_'.$updateid.'"  class="status_reply_'.$updateid.' input-custom2" placeholder="comment\'s"></textarea>'
                            . '<button id="reply_butn_'.$updateid.'" attr="'.$updateid.'" type="b" class="btn btn-warning pull-right btn-sm reply_butn reply_'.$updateid.'">Reply</button></div></div>';
                                
        }
}}                 
}?>
     

Thanks in advance.

Share this post


Link to post
Share on other sites
i managed to load contents from database dynamically using ajax

 

 

does that mean that the thread you posted on the forum a little over two hours ago no longer needs help? if so, please post a reply in it and mark it as solved/answered so that forum members don't waste their time reading it.

 

as to the problem in this thread. you haven't shown the javascript/jquery code that's attaching the events, but this is a common problem, and it's likely that you will need to use the .on() method, with the second parameter being the selector(s) you want to attach the event to. see the inormation about 'delegated events' at the following link - http://api.jquery.com/on/#direct-and-delegated-events

Share this post


Link to post
Share on other sites

ok, but how do i hide a item that should be hidden when it loads in to the document?? 

here is the jquery code that should hide the dynamically loaded elements

$(".hidden_textarea").hide();
$(".hidden_edit_4_session").hide();
$(".hidden_edit_4_friend").hide(); 

can you say it in layman terms as i'm learning jquery now.

Share this post


Link to post
Share on other sites

I think your best bet would be to add this to your CSS:

.hidden_textarea, .hidden_edit_4_session, .hidden_edit_4_friend {
  display: none;
}

Then in your javascript, when you actually want to show something, you toggle the class on that element

$('#element-i-want-to-toggle-visibility-of').toggleClass('hidden_textarea');

That will mean that any dynamically loaded data will be hidden by default, and only show once your code triggers it to be shown.

 

However, if you want to keep your implementation, then all you would need to do is add 

$(".hidden_textarea").hide();
$(".hidden_edit_4_session").hide();
$(".hidden_edit_4_friend").hide();

to the end of your $.post(); callback function, like so

$.post("st&com.php", {load:load},function(data){
  $("#status_area").append(data);
  $(".hidden_textarea").hide();
  $(".hidden_edit_4_session").hide();
  $(".hidden_edit_4_friend").hide();
});

Share this post


Link to post
Share on other sites

Just some learning tips:

 

It's quite common when people are starting up in ajax for them to get a bit confused about how and when to call aspects of the general page code.  Because ajax works outside the normal code flow it can be easy to forget that anything and everything that you want to be performed as a direct result of the ajax call must be included within the callback. For learning purposes I personally found it quite helpful to name the anonymous callback function to help remind me of the fact and got into the habit of using names such as:

 

$.ajax({
...
success: function everythingAfterDBSelect(data){
...
}
})

 

It's also worth saying that you can call existing page functions from within the callback as well, this can help keep the page code be a bit more readable as you can still group formatting code in the same area of the document, just within a function, and then call that function from the ajax callback to apply the formatting. 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.