简体   繁体   中英

Add a link to a div based on post's author status in real time

I have posts with unique id's that each goes green/grey if they author is logged in or logs off in real time (no refresh needed).

When the post is green (its author is online), I want its link to direct the user the a javascript function that will take the post id, title, etc.

When the post is grey, the link should direct the user to the post itself which means it will have to somehow get the $id of the post.

My problem is that all my php variables are set and work nicely if it's not real time, but if I want it real time, how can I pass these variables into the ajax code so it changes dynamically? Also, how can I make the whole div be a link and not just the text inside the div?

Main page

  $res = mysql_query("SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 10");
        if($res && mysql_num_rows($res) > 0){
            while($row = mysql_fetch_assoc($res)){
                $id = $row['id'];
                $user_id = $row['user_id'];
                $title = $row['title'];
            echo '<div class="status" id="user'.$user_id.'">'.$title.'</div>';
         }
    }

AJAX

    $(document).ready(function() {      
        setInterval(function(){
            $.ajax({
                url: 'status.php', //get online users
                dataType: "json",
                type: 'GET',
                success: function(data) {
                       if (data.length > 0){    // if at least 1 is online
                        $('.status').each(function(){                   // loop through each of the user posts                      
                        var userid = $(this).attr('id'); // get the user#
                        if($.inArray(userid, data) !== -1){  // if userid # in the returned data array set to online
                            $(this).css({background: '#40A547'}); 
                            $(this).wrapInner("<a href='javascript:void(0)' onclick='chatWith('.$id.')'></a>"); //call function for $id
                        } else{     // if not, set to offline
                            $(this).css({background: '#7f8c8d'});
                            $(this).wrapInner("<a href='post.php?id='></a>"); //take to post itself
                        }
                    });
                } else {    // if no one is online, set all to offline
                    $('.status').css({background: '#7f8c8d'});
                    $(this).wrapInner("<a href='post.php?id='></a>");
                }           
            }
        });
    }, 2000); //just for testing
 });

All help is much appreciated!

Here is how I would do it.

(1) Add the post id to the div , ie. data-postid="$id"

Main Page

$res = mysql_query("SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 10");
    if($res && mysql_num_rows($res) > 0){
        while($row = mysql_fetch_assoc($res)){
            $id = $row['id'];
            $user_id = $row['user_id'];
            $title = $row['title'];
        // add the $id to the div - ie. data-postid="$id"
        echo '<div class="status" id="user'.$user_id.'" data-postid='.$id.'" >'.$title.'</div>';
     }
}

(2) In the ajax, instead of using $(this).wrapInner() , I would just add an online class to those online using .addClass() , and remove it from those offline using .removeClass()

Ajax

$(document).ready(function() {      
    setInterval(function(){
        $.ajax({
            url: 'status.php', //get online users
            dataType: "json",
            type: 'GET',
            success: function(data) {
                   if (data.length > 0){    // if at least 1 is online
                    $('.status').each(function(){                   // loop through each of the user posts                      
                      var userid = $(this).attr('id'); // get the user#
                      if($.inArray(userid, data) !== -1){  // if userid # in the returned data array set to online
                        $(this).css({background: '#40A547'});
                        $(this).addClass('online'); 
                      } else{     // if not, set to offline
                        $(this).css({background: '#7f8c8d'});
                        $(this).removeClass('online');
                      }
                    });
                   } else {    // if no one is online, set all to offline
                    $('.status').css({background: '#7f8c8d'});
                    $(this).removeClass('online');
                   }           
            }
        });
    }, 2000); //just for testing
});

(3) Bind any click on your .status divs, get the post id, get if the post has the .online class, and then determine the link style. (note: add this inside the $(document).ready(function() { after your setInterval(function(){

$(document).ready(function() {
setInterval(function(){
 ...
}, 2000);

// Bind to any click on a post div
$('.status').click(function(){

    // get the post id
    var postid = $(this).data('postid');

    // check if post has '.online' class
    if($(this).hasClass('online')){

       // if online
       chatWith(postid);
    }
    else {

       // if offline
       window.location.href = 'post.php?id='+postid;
    }

});

});

here is a jsFiddle (it alerts the link/function with the id) - http://jsfiddle.net/f5xkZ/5/

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