Darktwen
Darktwen

Reputation: 343

Playing sound when new message comes in

I am making chat for my student group, and I am using AJAX to get my messages like this

//Initial call i make so user do not wait 2 seconds for messages to show
function marko() {
    $("#porukice").load("messages.php"); //Load the content into the div
}

marko();

//autorefresh every 2 seconds
var auto_refresh = setInterval(
(function () {
    $("#porukice").load("messages.php"); //Load the content into the div
}), 2000);

To send messages I am also using ajax, like this

var frm = $('#form1');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                document.getElementById("message").value = "";
                document.getElementById('play').play();
            }
        });

        ev.preventDefault();
    });

This is part of message.php (where messages are generated)

$sql = $conn->query('(SELECT * FROM chat ORDER BY time desc limit 0, 10) ORDER BY time');

while($row = mysqli_fetch_array($sql))
{
    $rows[] = $row;
}

foreach($rows as $row){ 
    $time = date('H:i:s', strtotime($row['2']));
    echo '['.$time.'] <b>'.$row['0'].'</b>: '.stripslashes($row['1'])."<br/>";
}

I am trying to play a sound when new message arrives> only solution I came up with is to play a sound when message is sent with

document.getElementById('play').play();

as you can see in above code. I have no clue how to play it when messages are coming, when mysql row is updated. I saw other answers on stackoverflow but they are not helping me.

NOTICE: $row['1'] is message, $row['0'] is user name and $row['2'] is time.

Upvotes: 1

Views: 2218

Answers (2)

Darktwen
Darktwen

Reputation: 343

I fixed this problem by creating separate file called sound.php
Sound.php is answering to get request with json response including date and time of last message

{"last_time":"2017-02-25 17:45:55"}

Then I am calling this file every 2 seconds with ajax, and if last_time has changed i play a sound

var skipped_once = false;
var old_time = 0

var auto_refresh = setInterval(function() {
$.get("sound.php", function(data) {
            // if old_time different than last_time play sound
        if (old_time != data.last_time) {
            //do not play sound on first page load
            if (skipped_once) {
                document.getElementById('play').play(); 
out.scrollTop = out.scrollHeight - out.clientHeight;
            }
            skipped_once = true;
            old_time = data.last_time;       
        }
    });
}, 2000);

Upvotes: 0

Condorcho
Condorcho

Reputation: 503

You could pass, from the PHP script that gets the messages, the value of the last id you got. Then, store it in a jQuery variable, and after you reload the messages, check if the ids are different, if they are (that means a new message came up), play the sound.

For example, after the foreach loop:

return json_encode(array('last_time' => $rows[count($rows)-1][2]));

On your jQuery:

var last_time = 0; // <--- New
var new_time = 0; // <--- New

// Initial call i make so user do not wait 2 seconds for messages to show
function marko() {
    $("#porukice").load("messages.php"); //Load the content into the div

    // New
    if (last_time < new_time) {
        document.getElementById('play').play(); 
        last_time = new_time;       
    }
}

marko();

//autorefresh every 2 seconds
setInterval(function () { // <--- Some edits here
    marko(); // <--- Some edits here
}, 2000);

// ....

var frm = $('#form1');
frm.submit(function (ev) {
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            document.getElementById("message").value = "";

            last_time = new_time; // <--- New
            new_time = data.last_time; // <--- New
        }
    });

    ev.preventDefault();
});

I've not tested this, but you're free to do it and let me know.

EDITED to use time instead of id

Upvotes: 1

Related Questions