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);
Related
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 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);
// ^^
So I've been stuck at this problem for quite a long time. Basically I have a button (#action) located in index.html. I have a second page : number.html. I'm trying to get in the .receiver span from index.html either .success content or .failure content from number.html, depending if #action was clicked in less than 2 seconds.
Here is the code :
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
});
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
});
Problem : on click, I never get the .success content, and I have no error message. But after 2 seconds, the .failure actually shows up. I tried several ways to make it work but it doesnt. I also checked if the flag value was changed on click with an alert box, and it was
You need to include the ajax calls within the on click function, otherwise the if logic will only be called when the page is loaded and never again.
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
flagCheck();
});
var flagCheck = function() {
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
}
});
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 have the following poll() function:
var pollTimeout = 5000;
(function poll(){
setTimeout(function(){
$.ajax({ url: "/ajax/livedata.php", success: function(data){
if (data[0] == 'success'){
// i'm doing some irrelevant updating here
}
poll();
}, dataType: "json"});
}, pollTimeout);
})();
It's being executed every 5 seconds and everything works fine.
However, how can I execute this function manually? For example, I need to execute it here:
$("#status-update-form textarea").keyup(function(e){
if (e.keyCode == '13'){
var status = $(this).val();
$.get("/ajax/update-status.php", { 'status' : status },
function(data){
$("#status-update-form textarea").val('').blur();
// <-- I need to execute the poll here, so that
// the status is updated immediatelly after it's
// submitted, not when the poll fires seconds later
},'json'
);
}
});
Any idea how can I do this? If I try to fire poll(), it says the function doesn't exist.
Convert your poll to a regular function
var pollTimeout = 5000;
function poll(timeout){
return setTimeout(function(){
$.ajax({ url: "/ajax/livedata.php", success: function(data){
if (data[0] == 'success'){
// i'm doing some irrelevant updating here
}
poll();
}, dataType: "json"});
}, timeout);
}
$("#status-update-form textarea").keyup(function(e){
if (e.keyCode == '13'){
var status = $(this).val();
$.get("/ajax/update-status.php", { 'status' : status },
function(data){
$("#status-update-form textarea").val('').blur();
poll(0);
},'json'
);
}
});
You could split the timeout code from the function it actually calls, then call it manually or automatically.
var pollTimeoutDelay = 5000;
var pollTimeout = null;
function pollNow(){
if (pollTimeout !== null);
clearTimeout(pollTimeout);
pollTimeout = null;
}
// do what you do, then in the callback:
timeout = setTimeout(pollNow, pollTimeoutDelay);
}
You can then call pollNow() whenever you like, it will do the thing, then re set the timeout again.
This method uses three variables in the global scope, if this is a large application it might be worth refactoring it some more.
I wouldn't use setTimeout() in a function in this case. This code below makes sure that the ajax request is killed every time you call poll() (once at start, every 5 seconds and every keyup event call)
var timeout;
var pollTimeout = 5000;
var ajaxCall;
function poll(){
if (null != ajaxCall) {
ajaxCall.abort();
}
ajaxCall = $.ajax({ url: "/ajax/livedata.php", success: function(data){
if (data[0] == 'success'){
// i'm doing some irrelevant updating here
}
poll();
}, dataType: "json"});
}
poll();
timeout = setTimeout(function(){
poll();
}, pollTimeout);
$("#status-update-form textarea").keyup(function(e){
if (e.keyCode == '13'){
var status = $(this).val();
$.get("/ajax/update-status.php", { 'status' : status },
function(data){
$("#status-update-form textarea").val('').blur();
poll();
},'json'
);
}
});