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

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);
}
})
}
});

Related

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 MySQL Query results in PHP

I have these DIVS which run PHP functions and return results. How can i make the returned results automatically refresh every X seconds without refreshing the whole page.
I just want to re-run the PHP/MySQL queries that are in the functions
<div class="container">
<div class="box"><h2>Callers Waiting</h2><?php echo CallersWaiting($queue_name, date('Y-m-d H:i:s', strtotime('-1 hour'))); ?></div>
<div class="box"><h2>Average Hold Time</h2><?php echo AverageHoldTime($queue_name, $date); ?></div>
<div class="box"><h2>Longest Wait Time</h2><?php echo LongestWaitTime($queue_name, $date); ?></div>
<div class="box"><h2>Shortest Wait Time</h2><?php echo ShortestWaitTime($queue_name, $date); ?></div>
</div>
UPDATE:
I have used this code:
<div class="container"></div>
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('.container').load('data.php', function(){
setTimeout(refreshTable, 2000);
});
}
</script>
then all my divs and PHP Functions run on a page called data.php but nothing is showing on my index.php page
<meta http-equiv="refresh" content="5; URL=http://www.yourdomain.com/yoursite.html">
regresh page after 5 sec and if you need js i can send it too
setTimeout(function(){
window.location.reload(1);
}, 5000);
For ajax you need a page that return all you data in Json or xml form.
then you need to make $.POST or $.GET or $AJAX request to that page and then parse it and then update your html elements.
example
http://danielnouri.org/notes/2011/03/13/an-ajax-page-update-mini-tutorial/
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('.container').load('data.php');
}, 2000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
<div class="container">Loading data ...</div>
If you need to refresh a page when clicking on a div, you can use AJAX Poll, but if you want to update the element every specific period, your code must be like so
$(document).ready(function () {
setInterval(function () {
$.ajax({
url: 'data.php',
type: 'get',
dataType: 'json',
success: function (data) {
$("#your-element-id").html(data.your_data);
},
error: function (ERROR) {
console.log(ERROR);
}
});
}, 2000); // trigger this function every 2 sec.
});

Trouble with dynamic refreshing div

I make div which refresh when file is updated. But it continuously refresh (fade out and fade in every second).I't source test2.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js>
</script>
<script>
$(document).ready(function() {
$('#loaddiv').load('check.chat.php');
});
var auto_refresh = setInterval( function() {
$.ajax(
{
type: 'POST',
data:"id=100",
url: "check.chat.php",
success: function(result)
{
if($("#loaddiv").html() != result)
{
$("#loaddiv").fadeOut("fast")
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
}
}
});
}, 1000);
</script>
<div id="loaddiv"></div>
And file on site: **
Who knows what's the problem?
This part:
$("#loaddiv").fadeOut("fast")
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
Should be:
$("#loaddiv").fadeOut("fast", function(){
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
});
In your case, both fades are called at the same time, making an animation queue, causing it to go from one phase to another in about the same time the interval triggers again.
UPDATE
To see logs, do this: console.log("html: ", $("#loaddiv").html(), "result: ", result);

First load issue, setInterval

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...

Refresh a table with jQuery/Ajax every 5 seconds

So I have a table pulling information from a database and I was wondering how I could make it refresh its information without reloading the whole page.
You'll need a getTable.php page that displays your table, and nothing else: no headers, footers, etc.
PHP (getTable.php) - this can be any server side code (asp, html, etc..)
<?php
echo '<table><tr><td>TEST</td></tr></table>';
?>
Then, in your JS, you can easily refresh the table by using the load() method:
HTML
<div id="tableHolder"></div>
JS
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>
Use ajax, following example is in jQuery:
$(function() {
var prevAjaxReturned = true;
var xhr = null;
setInterval(function() {
if( prevAjaxReturned ) {
prevAjaxReturned = false;
} else if( xhr ) {
xhr.abort( );
}
xhr = $.ajax({
type: "GET",
data: "v1="+v1+"&v2="+v2,
url: "location/of/server/script.php",
success: function(html) {
// html is a string of all output of the server script.
$("#element").html(html);
prevAjaxReturned = true;
}
});
}, 5000);
});
The success function assumes that your server script outputs the html that you want to replace in the element with id 'element'.
You should have a page that return the information and pull data using Ajax / jQuery.
<div class="result"></div>
setInterval(function() {
$.get('table.php', function(data) {
$('#result').html(data);
});
}, 5000);
Here is another option for you to use. This solution is using an IIFE which is preferred over setInterval. You can read more about IIFE at the link above.
JAVASCRIPT:
var $results = $('#results'),
loadInterval = 5000;
(function loader() {
$.get('script.php', function(html){
$results.hide(200, function() {
$results.empty();
$results.html(html);
$results.show(200, function() {
setTimeout(loader, loadInterval);
});
});
});
})();
HTML:
<div id="results"></div>
setTimeout(function(){
jqueryFunction(Args);
},100);
will work...
100 = 100 milliseconds
The following works with JQuery Datatables 1.10
`var tableName;
//Set AJAX Refresh interval.
$(function() {
setReloadInterval(10); //Refresh every 10 seconds.
}
//Because function takes seconds we * 1000 to convert seconds to milliseconds.
function setReloadInterval(reloadTime) {
if(reloadTime > 0)
internalId = setInterval("reloadTable()", (reloadTime * 1000);
}
//Auto Refresh JQuery DataTable
function reloadTable() {
tableName.ajax.reload();
}
//Table defined...
$(document).ready(function () {
tableName = $('#tableName').DataTable({
"sAjaxSource": "/someUrl",
});`

Categories