1

I am using PHP and MySQL to build a personal message system. The 'New-Message'-Counter needs to display the number of unread messages for each conversation. I am using a MySQL function to check the number of unread messages and a JQuery function to update the counter.

The problem is that the 'New-Message'-Counter is not working correctly. The expected output is to display the number of unread messages for each conversation. However, the variable countMessages doesn't contain the actual message count (as it is supposed to).

The SQL query to get the message count:

function check_unread_messages($chat_id, $from_id) {
    return (mysql_result(mysql_query("SELECT COUNT(*) FROM `messages` WHERE `group_id` = $chat_id AND `from_id` = $from_id AND `read_on` is NULL"), 0));
}

jQuery-Function where I call the SQL-query and try to update the div displaying the number of unread messages:

jQuery(document).ready(function() {
    jQuery(setInterval(function() {
        friends_count = document.getElementsByClassName("user").length;
        for(var i=1; i < friends_count+1; i++) {
            el = document.getElementById(i);
            conv_id = el.getAttribute("data-user-id");
            user_id = el.getAttribute("data-conv-id");
            my_user_id = "<?php echo $session_user_id; ?>";


            cache = "check_unread_messages("+conv_id+", "+user_id+")";
            countMessages = "<?php "+cache+" ?>";
            
            if(countMessages > 99) {
                countMessages = "99+";
            }

            if(countMessages > 0 || countMessages == "99+") {
                document.getElementById("badge-"+i).innerHTML = countMessages;
            }
        }
    }, 500));
});

And this is the Container for the Counter:

<div class="user" id='<?php echo $i ?>' data-user-id='<?php echo $user_id?>' data-conv-id='<?php echo $conversation['id'] ?>'>
    // something, that doesn't matter
    <?php // normaly php gets opend in "something, that doesn't matter"
    echo "<div class='rightCountUnreadMessages'>";
        echo '<div class="badge" id="badge-'.$i.'"></div>';
    echo "</div>";
    ?>
</div>

In the jQuery Function user_id and conv_id are correct as far as I can tell. I guess, that there is something wrong with the 2 lines after that (cache = ...)

Gykonik
  • 638
  • 1
  • 7
  • 24
  • You cannot mix javascript and php like that, they execute in two different environments. If you need to get info from a php script (without leaving the current page) you have to do an ajax request. – Patrick Evans Jan 20 '16 at 22:14
  • But with other functions (without parameters) it works like this... – Gykonik Jan 20 '16 at 22:15
  • 1
    First the php executes. Then it's done. Javascript executes on the client. After the php has finished. I don't think this code is doing what you think it's doing...$i has no meaning if you think javascript can pass it to the php script. – Nikki9696 Jan 20 '16 at 22:17
  • What other functions? You cannot create a variable in javascript and have php read it, which is what you are trying to do with `cache` – Patrick Evans Jan 20 '16 at 22:18
  • But with some other functions (like i said without parameters) it works fine... – Gykonik Jan 20 '16 at 22:19
  • A better solution for you would be a tiny php file that can be requested asych, that expects a posted variable. Have the javascript invoke it for each loop instead. – Nikki9696 Jan 20 '16 at 22:20
  • Ajax is client side and php is server side, when you need updates from the server side (like mysql calls), you have to do a post or do an AJAX call to a php script which returns your data. Olease look into Ajax or Jquery Ajax. – Dennis Heiden Jan 20 '16 at 22:20
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jan 20 '16 at 22:21
  • With other functions that have no parameters, the php is executing first, then returning. You don't notice any problem because you aren't trying to pass client side variables to a server side script. – Nikki9696 Jan 20 '16 at 22:21
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Jan 20 '16 at 22:21
  • The way I have done it works, without parameters but it seems so, that with parameters it doesn't work... – Gykonik Jan 20 '16 at 22:22
  • I cant work with Ajax pretty well, can anyone help me with my problem and solve it with Ajax please? :s... – Gykonik Jan 20 '16 at 22:23
  • As other commenters say, you seem to be mixing up server-side stuff (here php) with client-side stuff (here javascript). While it's true that you might render a php-variable like your `$session_user_id` onto your page (in a place that might happen to be some javascript), you still need some way of posting this to the server, e.g. an ajax-request (which I think is what you probably want). Quite frankly, I think you need to study some basics - e.g. you seem to be using your `countMessages` var as both a string and an int. Find some tutorials on php and javascript or maybe "web development" :) – Frederik Struck-Schøning Jan 20 '16 at 22:43

1 Answers1

1

Try to separate JS from PHP as possible, check the following example of how you can use AJAX requests to do that.

Create new PHP file called for example check_unread_messages.php contain :

$chat_id = $_POST['chat_id'];
$from_id = $_POST['from_id'];

$query = mysqli_query("SELECT COUNT(*) FROM `messages` WHERE `group_id` = chat_id AND 
          `from_id` = $from_id  AND `read_on` is NULL")

echo mysqli_result($query , 0);

And call it using ajax POST request $.post() like following :

$.post('check_unread_messages.php', {chat_id: conv_id, from_id: user_id}, function(result){
   //Here you get response of echo mysqli_result($query , 0); responce in 'result' variable
})

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101