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
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 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
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'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/
I have a reload function that reloads a page periodically. However, I would like to reload the page only if certain conditions are met (if not, increase the interval for the reload). So I tried using PeriodicalExecutor and an Ajax call like this -
<script type="text/javascript">
var nextReload = 10;
function reloadPage() {
document.location.reload();
return new PeriodicalExecuter(function(pe) {
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
var response = ...
nextReload = response.nextReload;
},
onFailure: function(){ ... }
});
this.frequency = nextReload; // doesn't do what I'd like it to do.
}, nextReload);
}
var myReload = reloadPage();
</script>
As you can see, the Ajax call returns the time (in seconds) in which the next reload should occur. However, I am not able to set the frequency of the PeriodicalExecutor to nextReload.
So how can I reload the page at variable time intervals?
Would something like this work for you?
<script>
function tryReload(){
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
if(transport == seconds){
// call self in x seconds
setTimeout(tryReload, (1000*transport));
}
else{ // transport is a URL
window.location = transport;
}
},
onFailure: function(){ ... }
});
}
//start it up!
tryReload();
</script>
Based on #Rocket Hazmat's suggestion, this worked for me -
function reloadPage() {
document.location.reload();
return new PeriodicalExecuter(function(pe) {
var that = this;
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
var response = ...
nextReload = response.nextReload;
that.frequency = next;
that.stop();
that.registerCallback();
},
onFailure: function(){ ... }
});
}, nextReload);
}