Is there any way to stay on a scroll position when an ajax is in refresh interval every 3 seconds? Here is the code that is in another webpage called "sample.php":
<script type="text/javascript" src = "includes/jquery.js"></script>
<script>
var inProcess = false;
setInterval( function () {
if (inProcess) {
return false;
}
inProcess = true;
jQuery.ajax({
url: 'data.php',
data: '',
method: 'POST',
success: function(answer) {
jQuery('#Load').html(answer);
inProcess = false;
},
error: function() {
inProcess = false;
}
});
}, 3000 );
</script>
<div id = "Load"> </div>
Inside data.php, I just run a query to echo out table rows. The ajax in sample.php, basically sends a request to data.php every 3 seconds to "repeat" the query so when a new value enters the database, it will automatically echo out after 3 seconds. It works but I would like the scroll position to stay where it is every time the ajax reloads.
Related
In the below code I am making an API call to my backend node.js app using setTimeout() which calls my AJAX at every 5 seconds. Inside my AJAX success I am displaying divContent1 & divContent2 based on certain condition which should execute at least once. After that only divContent2 should be visible at each setTimeout() calls.
index.html
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8070/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
//Some Task
}
});
$("#myButton").click(function(){
const route2 = function() {
$.ajax({
url: "http://localhost:8070/api/route2",
type: "POST",
dataType: "json",
data: { var1: val1 },
success: function (res) {
// Various tasks
if(res.flag){
$("#divContent1").hide();
$("#divContent2").show();
}
else{
$("#divContent1").show();
}
//Functions that handle div content data
},
beforeSend: function() {
$("#divContent1").hide();
$("#divContent2").hide();
},
complete: function() {
setTimeout(route2,5000);
},
});
};
$(function(){
route2();
})
});
});
</script>
The setTimeout() calls the entire route2 function which handles all the display and insertion of div content. However, the ask is to only display divContent2 from the second call.
Looking for a solution for this
The setTimeout() calls the entire route2 function which handles all
the display and insertion of div content. However, the ask is to only
display divContent2 from the second call.
You're calling route2 recursively with setTimeout(route2,5000); under complete. So this will run infinitely as complete occur each time an ajax call is completed (wether success or error). So what you can do is to create a timer and clear it after the second execution, something like this:
var ctr = 0, timer =0;
const route2 = function() {
$.ajax({
...
success: function (res) {
//Write you logic based on ctr
}
complete: function() {
if(ctr>0){
clearTimeout(timer)
}else{
timer = setTimeout(route2,5000);
ctr = ctr+ 1;
}
},
});
};
Will an external variable be enough? Just define it in the outer context and set/check it to choose the behavior:
// before declaring button click handler
var requestDoneAtLeastOnce = false;
// ...
// somewhere in success handler
success: function (res) {
if (!requestDoneAtLeastOnce) {
requestDoneAtLeastOnce = true;
// do something that belongs only to handling the first response
}
else {
// this is at least the second request, the other set of commands belongs here
}
}
This question already has an answer here:
Jquery button click event not firing
(1 answer)
Closed 8 years ago.
I have an auto refreshing HTML table with some buttons in it.
I current use the folowing Code to Refresh the Table every 5 seconds and set the ajax ClickListener. My problem is that the event ONLY fire before the first refresh fired.
<?php require_once ('UserTableHtml.php'); ?>
<script type='text/javascript'>
var table = $("#t02");
// refresh every 5 seconds
var refresher = setInterval(function()
{
table.load("UserTableHtml.php");
}, 5000);
table.ready(function()
{
$('.btnUser').click(function()
{
var clickBtnValue = $(this).val();
var ajaxurl = 'home.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response)
{
// Response goes here.
alert("action performed successfully");
});
});
});
</script>
The complete code of the output table is generated by the 'UserTableHtml.php'
Thanks for your answers an MERRY CHRISTMAS
If the problem is with the click of the button, you should use
$('.btnUser').on('click',function(){...});
Insted of
$('.btnUser').click(function(){...});
For dynamic elements, attach events using the .on() annotation.
Looks like it only loads after 5 seconds... add the line below to have it load after the table has finished rendering.
<script type='text/javascript'>
var table = $("#t02");
// refresh every 5 seconds
var refresher = setInterval(function()
{
table.load("UserTableHtml.php");
}, 5000);
table.ready(function()
{
$('.btnUser').click(function()
{
var clickBtnValue = $(this).val();
var ajaxurl = 'home.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response)
{
// Response goes here.
alert("action performed successfully");
});
});
//add this here...
table.load("UserTableHtml.php");
});
</script>
Guys i just figured it out.
Now it works as excepted.
var table = $("#t02");
table.ready(function()
{
$(document).on('click', '.btnUser',function()
{
var clickBtnValue = $(this).val();
var ajaxurl = 'home.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response)
{
// Response div goes here.
alert("action performed successfully");
});
});
});
<button type="submit" class="btnUser" name="userEdit" value="user_edit_'.$user->getId().'"><img src="images/edit-4.png" />
Apologies if this is a repost. I have seen many examples. But I can't seem to put together my needs.
I have a "today" page which displays all groups. Throughout the day more and more groups will appear. I want to be able to dynamically update these groups if the user has the page open and hasn't moved the mouse for X seconds. I have this chunk of code:
var timeout = null;
j$(document).on('mousemove', function() {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = null;
//calls another page to check if there's new data to display. if so, wipe existing data and update
j$.ajax({
url: "/include/new_Groups.php",
cache: false,
success: function(data){
j$( ".group_Container_Main" ).append( data ).fadeIn('slow');
}
})
.done(function( html ) {
});
}, 3000);
});
What this is doing is if the user hasn't moved the mouse after 3 seconds, do an AJAX call to update the group. This semi works. If you don't move the mouse, it will update. But it won't update again unless the mouse is moved and idle again for 3 seconds which is not good user experience.
I'm trying to find a way to just continually update the page every 3 seconds (for this example) if the user is idle. But if he's moving the mouse, there is to be no updating. Please ask questions if I'm unclear! Thanks in advance.
Should be straigh forward, use an interval and a function call instead
jQuery(function($) {
var timer;
$(window).on('mousemove', function() {
clearInterval(timer);
timer = setInterval(update, 3000);
}).trigger('mousemove');
function update() {
$.ajax({
url : "/include/new_Groups.php",
}).done(function (html) {
$(".group_Container_Main").append(html).fadeIn('slow')
});
}
});
FIDDLE
EDIT:
To solve the issue of stacking ajax requests if for some reason they take more than three seconds to complete, we can just check the state of the previous ajax call before starting a new one, if the state is pending it's still running.
jQuery(function($) {
var timer, xhr;
$(window).on('mousemove', function() {
clearInterval(timer);
timer = setInterval(update, 1000);
}).trigger('mousemove');
function update() {
if ( ! (xhr && xhr.state && xhr.state == 'pending' ) ) {
xhr = $.ajax({
url : "/include/new_Groups.php",
}).done(function (html) {
$(".group_Container_Main").append(data).fadeIn('slow')
});
}
}
});
On the AJAX parameter, use the complete option to trigger a mouse move :
j$(document).on('mousemove', function() {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = null;
//calls another page to check if there's new data to display. if so, wipe existing data and update
j$.ajax({
url: "/include/new_Groups.php",
cache: false,
success: function(data){
j$( ".group_Container_Main" ).append( data ).fadeIn('slow');
},
complete: function(data){
j$(document).trigger('mousemove');
}
})
.done(function( html ) {
});
}, 3000);
});
You can invert your timer idea to this logical connection...
Set a timer for 3 seconds after which you will do the AJAX call
If the mouse is moved, reset the timer for 3 seconds
You now have a three second timer running whether or not the mouse is moved and you reset it on mouse move to get the behaviour you want in respect of only updating on idle.
var timeout = setTimeout(update, 3000);
function update() {
clearTimeout(timeout);
//calls another page to check if there's new data to display. if so, wipe existing data and update
j$.ajax({
url: "/include/new_Groups.php",
cache: false,
success: function(data){
j$( ".group_Container_Main" ).append( data ).fadeIn('slow');
}
}).done(function(html) {
}).always(function() {
timeout = setTimeout(update, 3000);
});
}
j$(document).on('mousemove', function() {
clearTimeout(timeout);
timeout = setTimeout(update, 3000);
});
You should use setInterval() instead of setTimeout() to make a repeating event.
I would call setInterval() outside of your event handler code, and then make your event handler code update a lastTimeMouseMoved (or something) timestamp, which would be checked by the code passed to your setInterval() call.
So, your code might look like this:
const IDLE_TIME = 3000;
var lastTimeMouseMoved = Date.now();
timer = setInterval(function() {
if(Date.now() - lastTimeMouseMoved >= IDLE_TIME) {
//calls another page to check if there's new data to display. if so, wipe existing data and update
j$.ajax({
url: "/include/new_Groups.php",
cache: false,
success: function(data){
j$( ".group_Container_Main" ).append( data ).fadeIn('slow');
}
})
.done(function( html ) { });
} // end idle if
}, IDLE_TIME);
j$(document).on('mousemove', function() {
lastTimeMouseMoved = Date.now();
});
I want user to be logged out after some time inactivity. I want this php code to run automatically after some time of user inactivity. It must happen without refreshing the page.
<?php
if (isset($_SESSION['user_login_status'])) {
$max_time = 5; // Maximun inactive time(this time is set in seconds )
$current = time(); // Current time on server
if (!isset($_SESSION['Inactive']))
{ // Create session inactive;
Session::set('Inactive', time()); // Create session inactive;
} else {
$session_life = $current - $_SESSION['Inactive'] ;
if ($session_life > $max_time )
{
Session::destroy(); // This is a function that destroys all sessions and logging out the user
header('location: index.php'); // Redirects to some kinda page
} else {
$_SESSION['Inactive'] = time();
}
}
}
?>
This php code is working and user is logged out after 5 seconds when I refresh the page. But I need this code to be runned after those 5 seconds of inactivity and it should redirect to another page. I have tried some ajax code but it didn't worked.
Any suggestions how can I Run that php code after some time?
A lot of misspelled words. Sorry for that.
Modify the code according to your needs. What this code would do is that if the user refreshes the page within 5 second, the timer will reset and start the count again. If user does not refresh/reload the page within 5 seconds, ajax call will be made to your controller action to log the user off. Return a new url to the ajax call to automatically redirect user to a new page. [FYI, I do not like automatic logoffs, specially such short ones. Of course, most Web servers have session timeouts. I would rather go with those timeouts.]
// add these functions at the bottom of the output html page within <script> tags
// YOU SHOULD CALL setLogoutTimer FUNCTION ON MOUSEMOVE OR SOME USER ACTIVITY EVENT.
// otherwise user will be logged out even when the user is doing something on the page
setLogoutTimer();
function setLogoutTimer() {
var myTimeout;
if (window.sessionStorage) {
myTimeout = sessionStorage.timeoutVar;
if (myTimeout) {
clearTimeout(myTimeout);
}
}
myTimeout = setTimeout(function () { logoutNow(); }, 5000); //adjust the time.
if (window.sessionStorage) {
sessionStorage.timeoutVar = myTimeout;
}
}
function logoutNow() {
if (window.sessionStorage) {
sessionStorage.timeoutVar = null;
}
//MAKE AN AJAX CALL HERE THAT WILL CALL YOUR FUNCTION IN
// CONTROLLER AND RETURN A URL TO ANOTHER PAGE
$.ajax({
url: 'YOUR CONTROLLER ACTION URL',
cache: false,
async:false,
type: 'POST',
success: function (msg) {
window.location.href=msg; //msg is the url of another page returned by the controller
}
});
}
On my portfolio website, I am using a jQuery .ajax() call to pull in my portfolio pieces via XML.
My issue is that after a fresh page load, if the "portfolio" link is clicked first, then the portfolio pieces are pulled in normally. If, after a fresh page load, the "portfolio" link is clicked after any of the other links, then the portfolio pieces are pulled in twice.
You can see the issue for yourself on my site: Transhuman Creative
Here is the code that figures out which navigation link is clicked based on its rel attribute:
$("#nav a").click( function () {
if($(this).attr("rel") == "blog") {
return false;
}else{
$("#nav a").removeClass("selected");
$(this).addClass("selected");
setBlock($(this).attr("rel"));
}
});
After a link is clicked, it is processed by theThe setBlock() function, which hides existing content and calls the processBlock() function to load content.
function setBlock(block) {
if(firstNav) {
processBlock(block);
firstNav = false;
}
else
{
if($(".tab").length > 0 && $(".tab").is(":hidden") == false) {
$(".hidable").fadeOut();
$(".tab").fadeOut(function(){
processBlock(block);
});
}
else {
$(".hidable").fadeOut(function (){
processBlock(block);
});
}
}
}
The processBlock() function waits 500ms to let the animation finish, then either shows the block of content or calls the loadItems() function to load the portfolio data.
function processBlock(block) {
var s = setInterval( function () {
if (block == "portfolio") {
loadItems();
}else{
$("." + block).fadeIn();
}
clearInterval(s);
}, 500);
}
And finally, the .ajax() call is in the loadItems() function. After loading the porfolio data from the XML file, it calls the tabFade() function to parse the data and generate the HTML for the portfolio pieces. The variable firstCall is initially set to true, and it is meant to prevent the portfolio data from being reloaded if it's already in memory:
function loadItems() {
if (firstCall) {
$.ajax({
type: "GET",
url: "data/portfolio.xml?ver=1.11",
cache: false,
dataType: "xml",
success: function(xml){
$(xml).find('item').each(function(){
$("#main").append(addItem($(this)));
});
tabFade();
firstCall = false;
}
});
}else{
tabFade();
}
}
Any thoughts on what might be causing the double load issue? Thanks for your help.
I believe it would be better to set the firstCall variable right inside of the if condition. Otherwise it waits 500+ milliseconds before being set and only gets set once the ajax request completes.
function loadItems() {
if (firstCall) {
firstCall = false; // Put the assignment here before waiting.
$.ajax({
type: "GET",
url: "data/portfolio.xml?ver=1.11",
cache: false,
dataType: "xml",
success: function(xml){
$(xml).find('item').each(function(){
$("#main").append(addItem($(this)));
});
tabFade();
//firstCall = false;
}
});
}else{
tabFade();
}
}
Try using setTimeout instead of setInterval. You probably want to use setTimeout anyway as I don't think you want to run the code more than once?
It could be that it's running that code twice and making two ajax calls as it hasn't responded within 500ms.