I have this script
to get new messages from my database
setInterval(function () {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
}
});
}, 2000);
I am try to add a sound to it as soon as new data is added to the database
but when i add to the script
above, it plays the audio
every 2 seconds
(i think this is because its in the setInterval
)
setInterval(function () {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
var audio = new Audio('audio_file.mp3');
audio.play();
}
});
}, 2000);
So please i ask. How do i play sounds only when a new data has been added to the database?
I have this script
to get new messages from my database
setInterval(function () {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
}
});
}, 2000);
I am try to add a sound to it as soon as new data is added to the database
but when i add to the script
above, it plays the audio
every 2 seconds
(i think this is because its in the setInterval
)
setInterval(function () {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
var audio = new Audio('audio_file.mp3');
audio.play();
}
});
}, 2000);
So please i ask. How do i play sounds only when a new data has been added to the database?
Share asked Feb 25, 2017 at 13:31 Oke TegaOke Tega 88311 silver badges22 bronze badges 1-
is every time
response
is ing? – Death-is-the-real-truth Commented Feb 25, 2017 at 13:35
2 Answers
Reset to default 6Cache the last response
and pare it with the new version to determine whether or not to play the audio file.
var lastResponse = ''
setInterval(function() {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function(response) {
$(".msg_area").html(response)
if (lastResponse && response !== lastResponse) {
var audio = new Audio('audio_file.mp3')
audio.play()
}
lastResponse = response
}
});
}, 2000);
Edit: If you want audio to play the first time a response
es in, remove lastResponse &&
from the code above.
First of all , sure it plays every 2s because of setInterval()
You need to pare num of messages rows in your database before response and after.. for me the simple thing is to pass it inside hidden <div>
in your last message
setInterval(function () {
var message_num = // get the number from the last message
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
var new_message_num = // get the number from the last message after response
if(new_message_num > message_num){
var audio = new Audio('audio_file.mp3');
audio.play();
}
}
});
}, 2000);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742404200a4437511.html
评论列表(0条)