First load issue, setInterval - php

Using setInterval to reload a script - it does not reload before the first amount of time has passed (i.e: waits 120000 msec before actually displaying content). Is there a better way to do this?
<script id="source" language="javascript" type="text/javascript">
setInterval( "reloading();", 120000 );
$(function () {
reloading = function(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) + 1;
_val2 = val2;
$('#output').hide().html(timestamp +message ).fadeIn("slow");
$('#username').hide().html( vname ).fadeIn("slow");
}
});
}});
</script>

1 you are declaring reloading as a global variable and accessing it without knowing if your function is ready, that's not a good idea. If by any chance your site takes more than 2 minutes to load that will never work.
If you want to queue up your re-loads to process once every 2 minutes and run the first time without waiting, you can do it like this:
$(function(){
function reloading(){
//whatever you want to process goes here
(...)
setTimeout(function(){
reloading();
}, 120000);
}
reloading();
});
this will load your code once and then wait 12 seconds to run it again, and so on...

Related

How to expire ajax request link in PHP after certain Time Interval?

my ajax function will execute automatically by setInterval().
here i used Cache:false so on every request the time stamp will sent. but in php file i want to set expire for that timestamp. if the request received with existing time stamp should not return value.
$(document).ready(function(){
myVar = setInterval("asdFunc()", 1000);
});
function asdFunc(){
var date = new Date().getTime();
$.ajax({
type:"GET",
cache:false,
url:"rest.php",
data:{lest:"data"},
success:function(daa){
$('.response').html(daa);
}
})
}
<html>
<div class="response">
here will,
</div>
</html>
<script src="http://localhost/polt_s/assets/plugins/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(asdFunc(), 1000); //check here in your code
function asdFunc(){
var date = new Date().getTime();
$.ajax({
type:"GET",
cache:true, //cache = true, this will improve page performance
url:"rest.php",
data: {lest:"data"},
success:function(daa){
$('.response').html(daa);
}
})
}
});

how to make timer for ajax request in jquery

My question is i want to get total time of ajax request..
I means when i click on button then make a ajax request and start timer and store time in button caption,after ajax request success stop timer...
My problem is
when i click on button call ajax request and after ajax request successfully then timer start.
What i want
I want to start timer before ajax request and stop after ajax request success
My html code
<input class="btn green start_timer" value="Sync" name="btn" type="button">
My js code
$(document).ready(function () {
var setTimer = null;
$("body").on('click', '.start_timer', function () {
var obj = $(this);
var start = 1;
setTimer = setInterval(function () {
start++;
obj.val(start);
}, 1000);
$.ajax({
type: "POST",
url: base_url + "timerstart/start/1325",
async: false,
success: function (data) {
clearInterval(setTimer);
}
});
return false
});
});
You can use jQuery Global Ajax Event Handlers
Steps:
Use ajaxSend to trigger timer.
a. Display overlay.
b. Start the timer function. Use Interval to update timer on every second.
Use ajaxComplete to stop timer.
a. You can use ClearInterval to stop timer.
Calculate the difference incase you want that value to display after overlay is closed.
Notes:
Note that above mentioned global events will work as expected when there is only one ajax call at any moment of time.
You need to use Global variables to get the values from global events and calculate the difference.
Try this, its worked for me
$(document).ready(function () {
var setTimer = null;
$("body").on('click', '.start_timer', function () {
var element = $(this);
displayTimer(element);
});
function getData(element){
$.ajax({
type: "GET",
async:true,
url: "",
success: function (data) {
clearInterval(setTimer);
element.val("Sync");
},
error: function (data) {
clearInterval(setTimer);
element.val("Sync");
}
});
}
function displayTimer(element){
var start = 1;
setTimer = setInterval(function () {
start++;
element.val(start);
}, 1000);
setTimeout(function(){
getData(element);
},2000);
}
});
try this below updated:
<script>
$(document).ready(function () {
var setTimer = null;
$("body").on('click', '.start_timer', function () {
StartDispalyingTimer($(this));
});
RunAjax = function (ele){
$.ajax({
type: "POST",
async:true,
url: "index2.php",
success: function (data) {clearInterval(setTimer);},
error: function (data) {clearInterval(setTimer);}
});
}
StartDispalyingTimer = function (ele){var start = 1;
setTimer = setInterval(function () {start++;ele.val((start-1));}, 1000);
setTimeout(function(){RunAjax(ele);},1000);
}
});
</script>
You've got async=false in the options for your ajax request. This makes your request synchronous so the execution of the script "hangs" untill the request comes back with a response. You should never use async is false.

Auto Refresh JS Array if content changes?

I have this javascript function which serves an AJAX request to an external PHP Script, I want this to auto update a HTML <div> if the new check is different from the old check.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
This currently sucessfully returns and updates the div with the content from the array, the problem is, since adding the window.setInterval(function() line, it will server the connection every 5 seconds and update the <div> with duplicate data.. when all I want, it for it to echo the new data (if there is a ny)
Here is my other PHP script:
$STD = new mysqli ("localhost", "root", "hidden", "ajaxrequests");
$array = array();
$Query = $STD->prepare ("SELECT * FROM ajaxdata");
$Query->execute();
$Query->bind_result($ID, $Name, $Password);
while ($Query->fetch())
{
$array[] = array ( $ID, $Name, $Password);
}
echo json_encode($array);
Just add a call to empty() before your loop.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
Of course if your data size is large, this would not be very optimal. I would actually suggest having the PHP server send a timestamp value with it's response. You could then pass this back in subsequent AJAX requests and have the server determine if there are actually updates to deliver since that last timestamp. You could then have the server only send those updated records, which you could append/update similar to how you are already doing it.

jquery ui spinner(can not initialize after ajax call)

I've stuck into a problem and couldn't find the solution.I am using jquery ui spinner in a shopping cart.onchange of spinner it has to update the cart with ajax call.First time it work well with all cart update but on second time it won't call.I reinitialized it but still not working.Here is my sample code
$('.spinner').spinner({
min: 0,
stop: function(event, ui) {
var get_row_id = this.id;
var get_row_value = this.value;
var temp = get_row_id.split('_');
var row_id = temp[1];
var product_id = temp[2];
var checkout_flag = $("#hidden_checkout_flag").val();
var qty = $("#productqty_"+row_id+"_"+product_id).val();
$.ajax
({
type :"POST",
url : "client/cart/update_qty",
data :{'qty':qty,'product_id':product_id,'row_id':row_id}
dataType :'json',
success function(msg)
{
var value = eval(msg);
$(".order_box").html(value.sidebar_content);
$(".landing_cart_content").html(value.cart_content);
$(".out_of_stock_error").html(value.out_of_stock_error);
setTimeout(function() {
$(".out_of_stock_error").slideUp();
}, 4000);
$( ".spinner" ).spinner();//reinitialize
}
});
}
});
I have reinitialized it after ajax call and onChange of spinner it should again call the 'update_cart' function but it's not doing that. I've already wasted a whole day to solve this bit still no luck.
Any help will be highly appreciated,
Thanks

Execute function from another script in a script

I have two scripts running in the body of my page. When "a" is pressed on the keyboard, another script runs. How can I add some delay and then trigger the first script again? I have tried with the code below, it does not work. Prefferably, I would like to cancel the first timeout in the beginning of the second script as well.
<script id="source" language="javascript" type="text/javascript">
$(function (){
function reloading(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( vname +":" ).fadeIn("slow");
setTimeout(function(){
reloading();
}, 60000);
}
});
}
reloading();
});
</script>
<script>
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Message</i><br> <br>" +_val2 +" additional." ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
});
setTimeout("reloading()",1000);
</script>
You have to put reloaded() in global scope to access it from another script. Right now it is inside an anonymous function (a bit of a hack to mitigate global scope pollution), but for your case if it isn't feasible to merge the two scripts into one, you are going to have to pollute global scope.
If it is a one-off function, give it a unique prefix or something:
myApp_reloaded();
If you have a bunch of functions that need to be in the global scope, create a wrapper object. There are a bunch of different patterns you can use, I prefer this...
function MyApp() {
}
MyApp.prototype.reloaded = function () {
// reload func body here
}
var myApp = new MyApp();
now you can access the methods globally:
myApp.reloaded();
Quick hack until someone comes with a more elegant one that does not pollute the global scope
<script id="source" language="javascript" type="text/javascript">
var tId;
function reloading(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data) {
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( vname +":" ).fadeIn("slow");
clearTimeout(tId);
tId=setTimeout(function(){ reloading();}, 60000);
}
});
}
$(function (){
reloading();
});
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Message</i><br> <br>" +_val2 +" additional." ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(tId);
tId = setTimeout(function() { reloading()},1000);
});
</script>

Categories