Struggling to get this to work properly...Making an if/else statement with setInterval that if class is clicked, content refreshes, else content auto refreshes after a specific time period. This is what I have for just auto refreshing atm (which works perfectly):
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
What I've tried to get a "click" function added, but doesn't do anything...:
$('.contentTwoClicked').on('click', function() {
var refreshClicked = true;
if(refreshClicked) {
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
} else {
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
}
});
Where am I going wrong? Or am I way off-base here...? Any guidance/help would be greatly appreciated!
You don't need a conditional statement, but rather a variable to store the set interval in so that it can be cleared and restarted on manual refresh via a calling function:
//variable to store the setInterval
let refreshInterval = '';
//function that calls setInterval
const autoRefresh = () => {
refreshInterval = setInterval(()=> {
refresh();
console.log("auto");
},3000)
}
//run setInterval function on page load;
autoRefresh();
//manual refresh function
const manualRefresh = () => {
//erases the setInterval variable
clearInterval(refreshInterval);
refresh();
//then recalls it to reset the countdown
autoRefresh();
console.log("manual");
}
//for visual purposes
let refreshCount = 0;
//node refresher function
const refresh = () => {
const container = document.getElementById("refresh");
refreshCount ++;
container.textContent= "This div will be refreshed"+ ` Refresh Count: ${refreshCount}`;
}
<button onclick="manualRefresh()">Click to Refresh </button>
<div id="refresh">This div will be refreshed</div>
See it in action: https://codepen.io/PavlosKaralis/pen/rNxzZjj?editors=1111
Edit: Applied to your code I think it would be:
let interval;
var autoRefresh = () => {
interval = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000);
}
$('.contentTwoClicked').on('click', function() {
clearInterval(interval);
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
autoRefresh();
});
autoRefresh();
Related
I have the script working on nearly all devices. However, The Issue I am having is that the JavaScript doesn't work on an iPad 2, I need to allow this to work on an iPad 2, Either that or some other version of the script that detects that it is on an iPad 2 and uses a different script because of that.
This is the script I am using currently that doesn't support iPad 2:
<script>
$(document).ready(function() {
let location_one = document.getElementById('location1');
let location_two = document.getElementById('location2');
let getLocationOneData = function () {
$.ajax({
type: 'POST',
url: 'locationData1.php',
success: function(data){
$('#locationoutput').html(data);
}
});
};
let getLocationTwoData = function () {
$.ajax({
type: 'POST',
url: 'locationData2.php',
success: function(data){
$('#locationoutput').html(data);
}
});
};
let getData = function () {
if (location_one.checked) {
getLocationOneData();
} else if (location_two.checked) {
getLocationTwoData();
}
}
location_one.addEventListener('change', function () {
if (this.checked) {
getLocationOneData()
}
});
location_two.addEventListener('change', function () {
if (this.checked) {
getLocationTwoData();
}
});
getData();
setInterval(function () {
getData();
}, 120000); // it will refresh the data every 3 mins
});
</script>
I have code like this:
var saveToDB;
if ($('.new_article')[0]) {
saveToDB = function() {
var form;
form = $('.new_article');
$.ajax({
url: '/admin/articles',
type: 'POST',
data: form.serialize(),
beforeSend: function(xhr) {
$('.form-status-holder').html('Saving...');
},
success: function(data) {
var jqObj;
jqObj = jQuery(data);
$('.form-status-holder').delay(5000).hide();
}
});
};
$('form input, form textarea').on('input propertychange change', function() {
var timeoutId;
clearTimeout(timeoutId);
return timeoutId = setTimeout((function() {
saveToDB();
}), 5000);
});
return;
} else if ($('.edit_article')[0]) {
saveToDB = function() {
var form, id;
form = $('.edit_article');
id = (form.attr('action')).split("/").pop(-1);
$.ajax({
url: '/admin/articles/' + id,
type: 'POST',
data: form.serialize(),
beforeSend: function(xhr) {
$('.form-status-holder').html('Saving...');
},
success: function(data) {
var jqObj;
jqObj = jQuery(data);
$('.form-status-holder').delay(5000).hide();
}
});
};
$('form input, form textarea').on('input propertychange change', function() {
var timeoutId;
clearTimeout(timeoutId);
return timeoutId = setTimeout((function() {
saveToDB();
}), 5000);
});
return;
}
I got problem with setTimeout function in if condition while it cannot call to saveToDB inside. It takes me hours to find where is the problem come from but now I still get stuck. The second setTimeout function in else condition works correctly. Any help? Thanks in advance.
I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.
How can I have the ajax submit every x seconds, instead of each keyup after so many ms?
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
delay(function() {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Solution
Use setInterval It is like setTimeout but repeats itself.
setInterval(function () {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 1000);
Optimization
turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.
var saveToken;
var save = (function () {
var form;
return function () {
var form2 = $('#ajaxForm').serialize();
if (form !== form2) { // the form has updated
form = form2;
$.ajax({
type: "post",
url: "autosave.php",
data: form,
success: function(data) {
console.log('success!');
}
});
}
}
}());
$('.autosaveEdit').focus(function() {
saveToken = setInterval(save, 1000);
});
$('.autosaveEdit').focusout(function() {
clearInterval(saveToken);
save(); // one last time
});
I believe that what you are looking for is the window.setInterval function. It's used like this:
setInterval(function() { console.log('3 seconds later!'); }, 3000);
Use setInterval
function goSaveIt()
{
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}
setInterval(goSaveIt, 5000); // 5000 for every 5 seconds
I recently began learning Ajax and jQuery. So yesterday I started to programm a simple ajax request for a formular, that sends a select list value to a php script and reads something out of a database.
It works so far!
But the problem is, that when I click on the send button, it starts the request, 1 second later. I know that it has something to do with my interval. When I click on the send button, I start the request and every second it requests it also, so that I have the opportunity, to auto-refresh new income entries.
But I'd like to have that interval cycle every second, but the first time I press the button it should load immediately, not just 1 second later.
Here is my code:
http://jsbin.com/qitojawuva/1/edit
$(document).ready(function () {
var interval = 0;
$("#form1").submit(function () {
if (interval === 0) {
interval = setInterval(function () {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}, 1000);
}
return false;
});
});
Thanks!
I might be something like the following you're looking for.
$(document).ready(function () {
var isFirstTime = true;
function sendForm() {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}
$("#form1").submit(function () {
if (isFirstTime) {
sendForm();
isFirstTime = false;
} else {
setTimeout(function () {
sendForm();
}, 1000);
}
return false;
});
});
So, use setTimeout when the callback has finished as setInterval just keeps running whether or not your callback has finished.
$(function () {
$("#form1").submit(postData);
function postData() {
var url = "tbladen.php",
data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
setTimeout(postData, 1000);
}
});
return false;
}
});
Kind of related demo
I've done AJAX post loaders before but I'm having quite an hard time with jScrollPane.
Two things:
where should I load the posts? the div i created (#reviewspostscont) or .jspPane that JScrollPane makes? what if i have multiple loops then?
a more practical one now, this is the code i have so far, I can't get the function that triggers the AJAX to get the isAtRight variable (undefined in console), any fix?
Thanks in advance, Matt
$(function() {
$('#reviewspostscont').each(function() {
$(this).bind(
'jsp-scroll-x',
function(event, scrollPositionX, isAtLeft, isAtRight) {
console.log('Handle jsp-scroll-x', this,
'scrollPositionX=', scrollPositionX,
'isAtLeft=', isAtLeft,
'isAtRight=', isAtRight);
}
);
$(this).jScrollPane({ horizontalDragMaxWidth: 100 });
var api = $(this).data('jsp');
var throttleTimeout;
$(window).bind('resize', function() {
if (!throttleTimeout) {
throttleTimeout = setTimeout(function() {
api.reinitialise();
throttleTimeout = null;
}, 50);
}
});
});
$('#reviewspostscont').scroll(function() {
var $this = $(this);
var scrollWidth = $this[0].scrollWidth - $this.width();
var scrollPercentage = $this.scrollLeft() / scrollWidth * 100;
if (isAtRight == true) {
loadArticle(count);
count++;
}
});
function loadArticle(pageNumber) {
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop',
success: function(html) {
$("#reviewspostscont").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
});