In my project, I have a channel which displays videos at scheduled times. When there is not video at a time, in the place of div for displaying video, it will show an image with ID pgmimg.
<img id="pgmimg"/>
For implementing this feature I am calling a setInterval() which will check the current content in the video div. If it is the default image, then it will call an ajax function which will check whether there is any video at this time. If there is, then it will send the response.
$(document).ready(function() {
if ($('#pgmimg').length) // checking for next video only if there is no any video playing, ie., if the default image class is present
{
setInterval(function() {
nextchannel('<?php echo base_url();?>')
}, 3000);
}
});
function nextchannel(baseurl)
{
$.ajax({
type: 'post',
datatype: 'html',
url: baseurl + 'index.php/index/nextvideo',
success: function(response)
{
$('.videoarea').html(response);
}
})
}
PHP
function nextvideo()
{
$currentpgm = $this->db->query("query for fetching current programme");
$pgm = $currentpgm->row();
$currentpgnnum = $currentpgm->num_rows();
if ($currentpgnnum > 0)
{ // if there is any program at current time then display the video
echo '
<input type="hidden" name="starttime" id="starttime" value="' . $pgm->starttime . '"/>
<input type="hidden" name="currentdate" id="currentdate" value="' . $currentdate . '"/>';
}
else
{ // if there is no video, then show the default image with id pgmimg
echo '<img src="'.base_url().'images/video_sample.png" alt="video" id="pgmimg"/>';
}
exit;
}
Now the problem is that, it failed to check whether default image id is present or not (call setInterval only if default image id is present in the webpage) in the setInterval function $('#pgmimg').length. The video is playing,
but the setInterval() function is again getting called. But that should not happen.
Can anyone help me to fix this?
Thanks in advance.
Instead of setInterval use recursive setTimeout calls, so you can stop polling when needed. The added benefit of polling with setTimeout is if for some reason it takes longer than 3 seconds to get a response, you don't start making overlapping requests.
$(document).ready(function() {
if ($('#pgmimg').length) // checking for next video only if there is no any video playing, ie., if the default image class is present
{
setTimeout(function() {
nextchannel('<?php echo base_url();?>')
}, 3000);
}
});
function nextchannel(baseurl)
{
$.ajax({
type: 'post',
datatype: 'html',
url: baseurl + 'index.php/index/nextvideo',
success: function(response)
{
$('.videoarea').html(response);
if ($('#pgmimg').length) // call again if necessary
{
setTimeout(function() {
nextchannel('<?php echo base_url();?>')
}, 3000);
}
}
})
}
You need to do the test when the interval function runs, not when you're initially scheduling it:
$(document).ready(function() {
setInterval(function() {
if ($('#pgmimg').length) {
nextchannel('<?php echo base_url();?>');
}
}, 3000);
});
You did not clear the interval, so it gets called on and on.
Just save the interval to a variable:
var interval = window.setInterval(function() {
// check for the div
if($('#pgmimg').length > 0) {
nextchannel(url);
}
}, 3000);
function nextchannel(baseurl) {
// ajax ... success:
window.clearInterval(interval);
}
You are trying to implement wrong logic you need to implement
if($('#pgmimg').length > 0 )
I think this will solve your problem
Related
I'm facing an issue trying to implement notifications in my website.
In fact, I'm trying to make a function that calls PHP with an ajax request, in order to check with mysql if there are any notification. Then, if there is one/few notification(s), I get back from PHP the information I need, and display them using notification API. I do this every 5 seconds.
In fact, notifications are displayed in the top right corner, and I can only see the bottom of it.
Other weird fact, when I use function alert();, notifications are properly displayed.. This issue is happening with Firefox, but not on chromium.
So my question is, do you have any idea why notifications are not placed properly on firefox but not on Chromium? If you need any more information do not hesitate. Thanks in advance, and if you need it, here is some code :
With this two functions, I get what I need thanks to a php script.
function notifications() {
$.ajax({ url: './get_notifications.php/',
type: 'post',
data: {"name": window.user},
success: function(output) {
if (output != "")
{
split_notifications(output);
}
else
return;
},
failure: function() {
console.log("failed");
}
});
}
function check_notifications() {
setInterval(function() {
notifications();
}, 10000);
}
In this function, I just split information and then call another function, in charge of creating my notification.
function split_notifications(notif) {
var tmp_notif = notif.split(";");
var index = 0;
while (tmp_notif[0].split(",,,")[index])
{
//!\\ When I put alert() HERE it's working
display_notification(tmp_notif[1].split(",,,")[index], tmp_notif[2].split(",,,")[index], tmp_notif[0].split(",,,")[index]);
index += 1;
}
}
Here is the function that creates my notification :
function display_notification(title, message, someone) {
{
if(window.Notification && Notification.permission !== "denied") {
Notification.requestPermission(function(status) { // status is "granted", if accepted by user
var project_notification = new Notification(title, {
body: someone + " " + message + '\nSee more...',
icon: "../img/" + someone.split(" ")[1] + ".png"
});
project_notification.onclick = function() {
alert("");
}
});
}
}
<script>
Main Function:
var interval;
function refreshId(session_to_user) {
interval = setInterval(function()
{
$('.chat-box').load("<?php echo base_url()."users/message/refresh_div/"; ?>" + session_to_user);
}, 10000);
}
in this main function I'm only going to perform my requirement here. I have a variable interval my enabling this function, and it will refresh every 10 seconds.
onclick of function
forloop
{
<a href = "" onclick="myFunction(user_id)"
}
function myFunction(user_id){
clearInterval(interval);
$.ajax({
success:function(data)
{
$('.chats').html(data);
}
})
refreshId(session_to_user);
}
If anyone clicks on href, it should clearInterval if already exists else a new Interval has to be established on click function. In my current code, it works if I click for the first time. It starts refreshing the first link for every 10 seconds, but when I click for the second time on the second link, it waits. Still, the first one gets executed and then the second one is executing. My requirement is if I click, the established setInterval has to stopped instantly and the new one has to be started on the spot same as for my next function paper_plane() also.
function paper_plane()
{
clearInterval(interval);
$.ajax({
success:function(html)
{
$('#chat').append(html);
$('.chat-input').val('');
$('.chat-input').focus();
}
});
}
var side_bar_path = "<?php echo base_url()."users/message/load_side_bar"; ?>";
$.ajax({
success : function(data)
{
$('.msg-list').html(data);
}
});
refreshId(session_to_user);
}
There is no way you can cancel the ajax request after the delay(10 seconds) is elapsed from first click handler,since it would not return the result immediately.
so the only way you can cancel the previous ajax calls before making a new ajax call is to suppress/ignore the responses of the previous ajax calls once the second link is triggered, this way you will create a scenario what your expecting.
Below i have created a small snippet which will do the scenario mentioned above.
JS Code:
var firstTimer;
//first click handler
$('#first').on('click',function () {
firstTimer= setInterval(function (){
$.ajax({
url:"http://target.org/page.html",
dataType: "POST",
data:{'name1':'davy'}
success: function(data) {
//suppress the response when timer is stopped.
if(firstTimer>0){
return;
}
//if timer is not stopped process the data
},
error :function(error) {
//handle error
}
});
},1000);
});
//second click handler
$('#second').on('click',function () {
//clear the firstTimer before staring a new timer
clearInterval(firstTimer);
var timer;
timer = setInterval(function (){
$.ajax({
url:"http://target.org/page2.html",
dataType: "POST",
data:{'name1':'rog'}
success: function(data) {
//process the data
},
error :function(error) {
//handle error
}
});
},1000);
});
This question is based on this question; but, there are some differences.
My friend has an online webpage, which it has an inline script tag, there is a JavaScript function:
(#1):
var domain = window.location.protocol + "//" + window.location.host + '/';
$(document).ready(function() {
var count = 5;
countdown = setInterval(function() {
if (count == 0) {
$('#countdow').hide();
$('#link-news').show()
} else {
$('#countdow').text(count);
count--
}
}, 1700);
$('#link-news').click(function() {
var urls = $('input[name=linknexttop]').val();
if (urls == 1) {
$('input[name=linknexttop]').val(2);
$.ajax({
type: "GET",
url: domain + "click.html",
data: "code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
success: function(html) {
//alert(html);
window.location = html;
}
})
}
})
});
After waiting in 5 seconds, it will show:
(#2):
<div id="countdow">Please wait ...</div>
<img src="en_tran.png" border="0" name="imgTag" />
</div>
Now, I want to send data to click.html (in #1), without click into image imgTag (in #2). Is there possible to do it with JavaScript?
Rule for playing: "I am allowed to insert my code bellow his original code only; so, I am not allowed to change anything in his code. And, the most important: code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b is random.".
You can trigger the $('#link-news').click function by calling $('#link-news').click() after the 5 seconds countdown.
Or you can directly call the ajax call in the click function.
if (count == 0) {
$('#countdow').hide();
$('#link-news').show();
$('#link-news').click(); /* This will trigger the click event without actually clicking on the image */
} else {
$('#countdow').text(count);
count--
}
you can trigger click function without clicking on it using trigger function of jquery.
$( "#link-news" ).trigger( "click" );
What I am trying to do is detect whether there has been any new messages added to a conversation in a mysql database. If there is the I want to use JavaScript to scroll to the bottom of the page to the last message.
$(document).ready(function() {
var prevdata;
var interval = setInterval(function() {
$.ajax({
url: 'inc/aj_chat.php',
success: function(data) {
$('#messages').html(data);
afterdata = data;
}
});
setTimeout(function() {
alert(prevdata);
if (prevdata != afterdata) {
// Scroll Down function
}
prevdata = afterdata;
},1);
}, 3000);
});
as you can see I have a setInterval loop refreshing every 3000ms and im trying to pass the variables from the previous loop into the next loop to compare them. Firstly is this the best way to achieve this and secondly if it is how can I do this?
I would do something like this instead:
$.ajax({
url: 'inc/aj_chat.php',
success: function(data) {
$('#messages').html(data);
if($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
window.scrollTo(0,document.body.scrollHeight);
}
}
});
So everytime the scrollbar is 50 pixels or less from the bottom, it'll send the scrollbar to the bottom. If it's not, it'll leave the scrollbar alone. You can adjust the number 50 to any number of pixels you want.
So this will make sure your chatsystem auto-scrolls only if the user isn't searching in previous messages.
I have the following code build using jquery. When a user copies and pastes a a youtube url, i am suppose to extract the video id is the getVideoId(str) method in jquery. Using the id, i get the video image picture title and contents.
When the textbox->("#url") has a length more than 10, i will make a ajax request. Thus the ajax request is working. But now i have another problem. The very first time when the textbox has more than 10 characters, there is two ajax request being fired (tested using firebug). Than when the user enters more characters, there are many ajax request fired.
Thus this will slow down the process of the last ajax request. I just want to get the data of the youtube link and show a suggest where the user can add the title and content. It is like how the old facebook video video link is. Anyone has a better suggest in improving the codes?
jQuery(document).ready(
function(){
$("#url").keyup(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if($length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
alert('success in getting data');
}
});
return;
}
});
function getVideoId(str) {
var urlRegex = /(http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (urlRegex.test(str) && str.indexOf('v=') != -1)
{
return str.split('v=')[1].substr(0, 11); // get 11-char youtube video id
} else if (str.length == 11) {
return str;
}
return null;
}
}
);
You could cache the calls and use blur event and not keyup: you are firing a lot of AJAX call because keyup() fires an event each time a key is pressed, you should use blur that fires an event when an input loses focus.
If you cache the calls in an object you can avoid a lot of repeated calls
var cacheUrl = {};
$("#url").blur(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if(cacheUrls[$t1] !== undefined && $length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
//save the data to avoid a future call
cacheUrls[$t1] = data;
alert('success in getting data');
}
});
return;
}elseif ($length>10){
//you already have the data in cacheUrls[$t1]
}
});
EDIT if you want to use the submit key to start the search you could trigger the blur event when you press enter like this:
$("#url").keypress(function(e){
if(e.which == 13){
$(this).blur();
return false;
}
});
I think many ajax requests are fired because you are using $("#url").keyup(function()
so that for every key event in url input the particular funciton will exectue.So, as per i know better to use focusout method instead of keyup.
If you stay with the keyup-Event you maybe want to use an ajaxmanager-plugin for jQuery which can manage queues or limits the number of simultaneous requests.
$.manageAjax.create('myAjaxManager', {
queue: true,
cacheResponse: false,
maxRequests: 1,
queue: 'clear'
});
....
if($length>10){
$data = $.manageAjax.add({ ...
This will prevent having alot of ajaxrequests active at the same time when the user is typing. As soon as he stops the request will not aborted and the results will show up.