AJAX call instead of .click load - I would like the ajax to run every 3 seconds till the end of Total_Records. Here is my AJAX code which runs .click of a button.
I am passing two variables
1. id number
2. Total_Records
I would like the ajax to iterate a number of times = Total_Records.
Any suggestions are highly appreciated.
$(document).ready(function() {
$(document).on('click', '.show_more', function() {
var ID = $(this).attr('id');
var lim = $(this).attr('Total_Records');
$.ajax({
type: 'POST',
url: 'moreajax.php',
data: {
'id': ID,
'lim': lim
},
success: function(html) {
setTimeout(function() {
$('#show_more_main' + ID).remove();
$('.postList').append(html);
}, delay);
},
});
});
});
Method 2) Please kindly read and recommend any better way or script improvement with examples please. this will benefit everyone.
Note: I believe this method would be a great enhancement and re-usable to lots of people who are looking for interval runs.
The only issue is the cancel button .click is not stopping the ajax call.
$('#cancel').click(function() {
cancel = true;
});
$(function() {
//If cancel variable is set to true stop new calls
if (cancel == true) return;
var RecordsInterval = 10 * 1000;
var fetchRecords = function() {
console.log('Sending DATA AJAX request...');
$.ajax({
type: "POST",
url: "fetchRecords.php",
data: {
'id': ID,
'lim': lim
}
}).done(function(html) {
$('#show_more_main' + ID).remove();
$('#postList').append(html);
alert("You got it champ")
console.log('success');
console.log('Waiting ' + (RecordsInterval / 1000) + ' seconds');
setTimeout(fetchRecords, RecordsInterval);
}).fail(function() {
console.log('error');
alert("error Champ");
return;
});
}
// Fetch Records immediately, then every 10 seconds AFTER previous request finishes
fetchRecords();
});
Related
I'm trying to get the time between when the user clicks the start button and the stop button. I was able to start and stop the time but I can't get the time. I'm using ajax success function to call clearInterval function to stop the time so when I successfully inserted my data. The time will stop and I need to get the time after the stop button is clicked.
I just need to get the variable cons. below is my code:
$(".start").click(function() {
var sec = 0;
var cons = 0;
siID = setInterval(function() {
cons = sec++;
console.log(cons);
}, 1000);
});
$('.stop').click(function() {
$.ajax({
url: "Register_c/register_data",
method: 'POST',
async: false,
data: {
registration: {
TIN: '123'
}
},
success: function(data) {
window.clearInterval(siID); //stops the counting
alert(cons); //here i can't get the variable cons
},
error: function(xhr, status, error) {
alert('failed');
}
});
As many have pointed out, you need to move cons into the global scope, I'd also recommend using performance.now() as it gives a more accurate time over Date.now(). Another point, you want to know the difference before calling the AJAX request otherwise it's more of the time difference between the user clicking start then stop and then the request finishing rather than just the user clicking start and then stop.
var cons = null;
$(".start").click(function () {
cons = performance.now();
});
$('.stop').click(function () {
alert(performance.now() - cons); //Difference in Milliseconds
$.ajax({
url: "Register_c/register_data",
method: 'POST',
data: {
registration: {
TIN: '123'
}
},
success: function (data) {
},
error: function (xhr, status, error) {
alert('failed');
}
});
});
var cons = null;
$(".start").click(function() {
cons = performance.now();
});
$('.stop').click(function() {
console.log("Call to stop took " + ( performance.now() - cons) + " milliseconds.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="start">Start</button>
<button class="stop">Stop</button>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var sec =0;
var cons =0;
var start = $('#start').click(function() {
siID = setInterval(function() {
cons = sec++;
console.log(cons);
}, 1000);
return cons;
});
$('#stop').click(function() {
alert(cons);
$.ajax({
url: "Register_c/register_data",
method: 'POST',
async: false,
data: {
registration: {
TIN: '123'
}
},
success: function(data,start) {
window.clearInterval(siID); //stops the counting
alert(start); //here i can't get the variable cons
},
error: function(xhr, status, error) {
alert('failed');
}
});
});
});
</script>
</head>
<body>
<button id="start">start</button>
<button id="stop">stop</button>
</body>
</html>
I have added the start function and it returns the cons and able to display that in an alert on clicking the stop function.
Your variable cons is a local scope so it is not available in another method where you are trying to display it, that is reason why you should move it up to a global scope
A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it, and that's what you need.
But also I would recommend you to use console.time (non-standard) to measure execution time of your registration method:
console.time('someFunction');
someFunction(); // run whatever needs to be timed in between the statements
console.timeEnd('someFunction');
or you could use the standard performance.now() API, like so:
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
I hope this will help you..
document.getElementById("uploadUpdate").addEventListener("click", function() {
intervalVarUpload = setInterval(function () {
console.log("Updating table..");
Object.keys(arrExplores).forEach(function (key) {
if(arrExplores[key][2] != "Not"){
//remoteArrUpdate makes a ajax call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}, 2000);
console.log("Interval started!");
});
document.getElementById("uploadStop").addEventListener("click", function() {
clearInterval(intervalVarUpload);
});
function remoteArrUpdate(id, key) {
$.ajax({
url: 'https://offcloud.com/api/remote/status',
data: {'requestId' : id},
type: 'POST',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data) {
arrExplores[key] = [arrExplores[key][0],key,data.status.requestId,data.status.status, data.status.fileSize];
explorArrToTable();
},
error: function() {
console.log('Failed!');
}
});
}
So, at the moment, a uploadUpdate button is clicked and an interval is started to go through an array and make a ajax on every object and update that object. However, I don't want to use an interval because sometimes the next interval will start before the previous is finished and sometimes there is a long wait time. I want the next interval to start as soon as the previous interval has either successfully or unsuccessfully finished all ajax calls, to start at the beginning of the array again and start making the same ajax calls, until the uploadStop button is pressed. How would i change the two button functions to do this?
Just tried to mimic your ajax calls using a setTimeout. You could use it in your ajax success / failure. I think, you need some code refactoring to accomplish this. Hope this helps / point you in the right direction.
var intervalVarUpload;
document.getElementById("uploadUpdate").addEventListener("click", function() {
uploadUpdate();
});
function uploadUpdate() {
//Start the Interval
intervalVarUpload = setInterval(doSomething, 2000);
console.log("Interval started!");
}
document.getElementById("uploadStop").addEventListener("click", function() {
console.log("Interval Stopped");
//Clear the Interval
clearInterval(intervalVarUpload);
});
function doSomething() {
//Clear the Interval so as to hold on till the current method call is complete.
clearInterval(intervalVarUpload);
console.log("Updating table..");
var arrExplores = {
customArray: ["Yes", "Not", "Hello"]
};
Object.keys(arrExplores).forEach(function(key) {
if (arrExplores[key][2] != "Not") {
//remoteArrUpdate makes a json call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}
function remoteArrUpdate(id, key) {
setTimeout(function() {
//Consider as a ajax complete
uploadUpdate();
}, 2000)
}
<button id="uploadUpdate">Upload Update</button>
<button id="uploadStop">Upload Stop</button>
I've watched several tutorials on how to load content without having to refresh the browser. I'm also using history pushState and popstate to update the url dynamically depending on what site that is displaying. However even if this code works, I would like to be able to make som page transition animation effects > call the Ajax function > then make some fadeIn animation effects. So far i've had no luck in trying to do so. I tried to read up on Ajax (beforeSend: function(){}), but the success function seems to execute before the (beforeSend) function. Is there anyone that could point me in the right direction, or tell me what i possibly am doing wrong? I'd appriciate it!
$(document).ready(function() {
var content, fetchAndInsert;
content = $('div#content');
// Fetches and inserts content into the container
fetchAndInsert = function(href) {
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
content.html(data);
}
});
};
// User goes back/forward
$(window).on('popstate', function() {
fetchAndInsert(location.pathname);
});
$('.buttonlink').click(function(){
var href = $(this).attr('href');
// Manipulate history
history.pushState(null, null, href);
// Fetch and insert content
fetchAndInsert(href);
return false;
});
});
Questions? Just ask!
Thanks beforehand!
/// E !
You need to use callbacks. The provided solutions will work, but not necessarily sequentially. $.animate() and $.ajax both run asynchronously. If unfamiliar with this term, here's a good intro: http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027
Here's what I might do:
fetchAndInsert = function(href) {
$('#some-element').animate({'opacity':'0.0'}, 1000, function () {
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
content.html(data);
content.animate({'opacity':'1.0'}, 1000);
}
});
});
};
That will fade out whatever is currently in content, fetch the new data, replace what's currently in content, and then fade back in.
I tried to read up on Ajax (beforeSend: function(){}), but the success
function seems to execute before the (beforeSend) function
You can wait for animation to complete before appending new content to html using .queue(), .promise(), .finish()
beforeSend: function() {
element.queue(function() {
$(this).animate({/* do animation stuff */:500}, {duration:5000}).dequeue()
});
},
success: function(content) {
element.finish().promise("fx").then(function() {
container.append(content).fadeIn()
})
}
var element = $("#loading").hide();
var container = $("#content");
var button = $("button");
var ajax = {
// do asynchronous stuff
request: function() {
return new $.Deferred(function(d) {
setTimeout(function() {
d.resolve("complete")
}, Math.random() * 5000)
})
},
beforeSend: function() {
element.fadeIn().queue(function() {
$(this).animate({
fontSize: 100
}, {
duration: 2500
}).dequeue()
});
},
success: function(content) {
element.finish().promise("fx").then(function() {
element.fadeOut("slow", function() {
$(this).css("fontSize", "inherit");
container.append(content + "<br>").fadeIn("slow");
button.removeAttr("disabled")
})
})
}
}
button.click(function() {
$(this).attr("disabled", "disabled");
$.when(ajax.beforeSend()).then(ajax.request).then(ajax.success)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="loading">loading...</div>
<div id="content"></div>
<button>load content</button>
jsfiddle https://jsfiddle.net/ajmL5g1a/
Try this:
fetchAndInsert = function(href) {
// Before send ajax. Do some effects here
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
// After loading. Do some effects here
content.html(data);
}
});
};
My solution:
fetchAndInsert = function(href) {
var timeBeforeAnimation = Date.now(), animationDuration = 500;
/* Do some animation, I assume that with jQuery,
so you probably know how much time is takes - store that
time in variable `animationDuration`. */
/* Run your "before" animation here. */
$.ajax({ ...,
success: function(data) {
/* Check, if request processing was longer than
animation time... */
var timeoutDuration = animationDuration -
(Date.now() - timeBeforeAnimation);
/* ...and if so, delay refreshing the content,
and perform the final animation. */
setTimeout(function() {
content.html(data);
/* Perfom final animation. */
}, Math.max(0, timeoutDuration);
}
});
};
I would probably try using some css for this.
#content {
opacity: 0;
transition: all 1s;
}
#content.fade-in {
opacity: 1;
}
...
const content = $('#content');
const btn = $('.buttonlink');
const success = data =>
content.html(data).addClass('fade-in');
const fetchAndInsert = url =>
$.ajax({ url, cache: 'false' }).done(success);
const getData = function(e) {
e.preventDefault();
content.removeClass('fade-in');
fetchAndInsert($(this).attr('href'));
};
btn.on('click', getData)
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