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
Related
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 have a js structure like this:
var intervalID;
function counterUpdater(){
intervalID = setInterval(ajax_counter_upload(),10000);
}
function ajax_counter_upload(){
$.ajax({
type: "POST",
url: "plan/counter.php",
data: {tipo:'BP'},
success: function(data){
$("#spinner_msg").fadeTo(200,0.1,
function(){
$(this).html(data);
$(this).fadeTo(900,1);
});
}
});
}
function ajax_submit(){
var submit_val=$("#stato").serialize();
dest="plan/new_bp1.php";
$.ajax({
type: "POST",
url: dest,
data: submit_val,
success: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_success").html(data1[1]).fadeTo(900,1)});
}else if(data1[0]=="Errore"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_error").html(data1[1]).fadeTo(900,1)});
}
},
complete: function(){
clearInterval(intervalID);
setTimeout(function(){ $('.container').load('plan/home.php');},2000);
}
});
setTimeout(function(){counterUpdater();},2000);
}
Goal would be to run counter_updater each 10 seconds when the ajax_submit starts and to stop it when the ajax_submit ends.
What I get now is to run counter_updater only once.
What am I doing wrong?
There's a mistake in your setInterval call: you have parentheses after the (intended) callback function name, which means that the function is actually called once and setInterval gets only the return value (nothing, in this case).
Simply remove the parentheses:
intervalID = setInterval(ajax_counter_upload, 10000);
// ^^
setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
var url = '/Lines/dbcheck/?LineID=#ViewBag.LineID&ProductID=#ViewBag.ProductID&LastID=#LastID';
var data = {};
$.get(url, data, function(response_text){
if (response_text == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
}, "text");
}
I already can call function from controller but only 1 time. I would like to create function to check the data from database and return 1 or 0. If it is 0 i would like to make a delay for 5 sec and then recall function again.
the problem is the parameter response_text is not updated because I can call the function from controller only first time
setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
$.ajax({
cache : false,
dataType: "json",
type: "GET",
async:false,
url: url ,
success: function (fdata) {
if (fdata == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
},
error: function (reponse) {
}
});
}
Your code executed immediately because of you passing () it is not wait for the time delay.
setInterval(makeAjaxCall(), 5000);
change to
setInterval(makeAjaxCall, 5000);
or alternate way
setInterval(function() {
makeAjaxCall();
}, 5000);
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'm currently building a simple AJAX call application which will show the result of a textbox after typing some texts inside it:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(document).ready(function(e) {
$("input[name=html]").keyup(function(e) {
if(this.value.length > 1) {
e.preventDefault();
var form = $(this).closest('form');
var form_data = form.serialize();
var form_url = form.attr("action");
var form_method = form.attr("method").toUpperCase();
delay(function(){
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
$("#loadingimg").hide();
}
});
},1000);
}
});
});
Fiddle Demo
As you can see from the demo above, for instance if you type test,test1 or test2 or any word as long as their length is longer than one then it'll make an AJAX call.
My question is that is there any way that allow me to prevent duplicate AJAX call? For example if I type test in the textbox again, it'll immediately show test in the div without making another AJAX call to fetch the result again. Thank you very much in advance.
You just need to cache previous results and, before making the ajax call, check the cache to see if you already have that result in the cache.
In Javascript, one usually uses an object for a cache:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
// create cache for ajax results
// the key is the form_data
// the value is whatever the ajax call returns
var ajaxCache = {};
$(document).ready(function(e) {
$("input[name=html]").keyup(function(e) {
if(this.value.length > 1) {
e.preventDefault();
var form = $(this).closest('form');
var form_data = form.serialize();
// check the cache for a previously cached result
if (ajaxCache[form_data]) {
// this uses delay, only so that it clears any previous timer
delay(function() {
$("#result").html(ajaxCache[form_data]);
$("#loadingimg").hide();
}, 1);
} else {
var form_url = form.attr("action");
var form_method = form.attr("method").toUpperCase();
delay(function(){
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
// put this result in the cache
ajaxCache[form_data] = returnhtml;
$("#loadingimg").hide();
}
});
},1000);
}
}
});
});
Working demo: http://jsfiddle.net/jfriend00/P2WRk/