how to make timer for ajax request in jquery - php

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.

Related

jQuery Live Search keyup show loading

I am trying to display a loading animation and hide the search input box before the ajax request has been sent, the ".se-pre-con" element is the loader.
As you can see below I am tring to show this in the beforeSend of the ajax request. However, when the user is typing in the search box then stops for the delay specified (1000ms) the input box still displays throughout the ajax request but it is unresponsive.
Then the results are returned, and the loading animation does the fadeOut so it the show() must be triggering but the page remains unchanged until the results are returned. I want to prevent the unresponsive page effect and show a loading animation during the request. Any help is much appreciated.
$(document).ready(function() {
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('#search_field').keyup(function() {
var target = $(this);
delay(function() {
getSearchResults(target.val());
}, 1000);
});
function getSearchResults(str) {
$.ajax({
beforeSend: function(){
$(".se-pre-con").show();
$("#search_field").hide();
},
url: "http://example.com/Search_Results.php",
dataType:"html",
data: {"search_term": str},
method: "post",
async: false,
success: function(data){
if(data !== null) {
$("#search_default").hide();
$("#search_results_wrapper").html(data);
}
$(".se-pre-con").fadeOut("slow");
$("#search_field").show();
$("#search_field").focus();
},
error: function(){
$(".se-pre-con").fadeOut("slow");
$("#search_field").show();
$("#search_field").focus();
}
});
}
});
I found the solution.
Solution
It started working when I removed the option:
async: false

Issue updating a <div> via AJAX refresh

I am dynamically generating a web page via scriptA.php. Within this page,
I have a div element #WatchContainer that needs to be updated every 5 minutes. The content for #WatchContainer is created by scriptB.php. To accomplish this, I have used "include" to embed scriptB.php in scriptA.php. The variable $sum is defined in scriptA.php and used by scriptB.php to update the content in #WatchContainer.
On initial page load, $sum is correctly passed from scriptA.php to scriptB.php. However, when #WatchContainer is updated via AJAX request, $sum is no longer passed to scriptb.php. The jQuery function is as follows:
function updateWatch() {
$.ajax({
url:"scriptB.php",
success: function(data) {
$("#WatchContainer").html(data);
}
});
}
var WatchInterval = setInterval("updateWatch()", 300000);
i don't see you passing any variable to scriptB.php via ajax.
i thinnk you should pass your $sum variable to scriptB.php via ajax using POST OR GET method
POST
function updateWatch(sum) {
$.ajax({
type:"POST",
url:"scriptB.php",
data:"sum="+sum,
success: function(data) {
$("#WatchContainer").html(data);
}
});
}
GET
function updateWatch(sum) {
$.ajax({
type:"GET",
url:"scriptB.php?sum="+sum,
success: function(data) {
$("#WatchContainer").html(data);
}
});
}
Try this with 3 seconds interval time, and make sure you include the library and other related stuff.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
var WatchInterval = setInterval(function() {
$.ajax({
url:"scriptB.php",
success: function(data) {
console.log(data);
}
});
},3000);
});
<script>

auto refresh ajax div running on php page

Please see my code below. I want to auto refresh a div on a php page. I tried to refresh through javascript and html header, but it is slowly slowing down my computer.
page2.php
<?php
if($_GET['type']!='ajax'){
include 'header.php';
echo "<div id='main-content'>";
}
?>
Itm 1</br>
Itm 2
<img class="ajax-loader" src="ajax-loader.gif" alt="loading..." />
<?php
if($_GET['type']!='ajax'){
echo "</div>";
include 'footer.php';
}?>
app.js
$.cergis = $.cergis || {};
$.cergis.loadContent = function () {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
if (pageUrl != window.location) {
window.history.pushState({ path: pageUrl }, '', pageUrl);
}
}
$.cergis.backForwardButtons = function () {
$(window).on('popstate', function () {
$.ajax({
url: location.pathname + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
}
});
});
}
$("a").on('click', function (e) {
pageUrl = $(this).attr('href');
$.cergis.loadContent();
e.preventDefault();
});
$.cergis.backForwardButtons();
i have tried different variation but no luck. please help me.
thanks.
app.js changed...
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
}
setInterval(function(){myTimer()}, 1000);
Try setTimeout:
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
setTimeout(myTimer,1000);//so that the request ends setTimeout calls a new request.
},
error: function () {
setTimeout(myTimer,1000);//If there is an error in the request the "autoupdate" can continue.
}
});
}
myTimer();//fire
this way setTimeout() waiting to finish the request to invoke a new request.
setInterval() does not wait, which makes simuntaneos generate multiple events, which causes the slowness.
You can use setTimeout($.cergis.loadContent, 1000); to refresh once or setInterval($.cergis.loadContent, 1000); to refresh each seconds (1000 milliseconds = 1second).
See http://www.w3schools.com/js/js_timing.asp

Jquery stop function when user hovers over a div

I have a jquery ajax function:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
And I want to stop the function when a user hovers over the div 'Posts' and resume when the user stops hovering over that div. Is there any way I could do that.
Thanks
Here you go :)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
timer = setTimeout(posts,2000);
}
});
}
posts();
$(document).ready(function(){
$('#posts').hover(function(){clearTimeout(timer);}, function(){setTimeout(posts,2000);});
});
</script>
<div id = 'posts'></div>
Basically I added a mouser-over and mouse-out event handlers to the #post div which will clear and reset the timeouts respectively..
you probably wnat to stop ajax function from running what you are looking for is called
var pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
more on hover event
$("idofyourdiv").hover(
function () {
pfunc.abort();
},
function () {
pfunc();
}
);
First, I'd structure your base code somewhat like this:
var timer = null;
var request = null;
function posts() {
request = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data).fadeIn(2000);
timer = setTimeout(posts, 2000);
}
});
}
posts();
Next, to clear the timer, run clearTimeout() on the timer object. timer stores the id of your timeout function, which might not exist when you try to clear it, so safely clear it like this:
if (timer !== null) {
clearTimeout(timer);
}
Finally, you should abort the AJAX request, so just add that in as well:
if ((timer !== null) && (request !== null)) {
clearTimeout(timer);
request.abort();
}
This one will check if your div is being hovered. And if it is true, the ajax call will be cancelled.
Trying not to modify too much your code:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
beforeSend: function(){
if($("#posts").is(":hover")){
return false;
}
},
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
javascript is not multi threaded so you can not stop a piece of code from running. As stated in other answers you may call abort on your ajax request but that is not stopping any code, it just aborting a request. And I'm not even sure its smart to abort the request when your just going to make the request again when the user stops hovering. I would let the request go thru and check the hover state in the response. If the hover state does not match your condition buffer the response and wait till the user stops hovering then resume your execution. Something like the following...
var hovering = false;
var onResponse = null;
$('.Posts').mouseover(function() {
hovering = true;
});
$('.Posts').mouseout(function() {
hovering = false;
onResponse && onResponse();
});
function posts() {
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
onResponse = function() {
if(hovering) return;
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts, 2000);
onResponse = null;
};
onResponse();
}
});
}
posts();

jQuery constantly ping for Ajax responce

How can I use jQuery to constantly run a PHP script and get the response every second and also to send small bits of data on mouse down to the same script?
Do I really have to add some random extension just to get such a simple timer to work?
To iterate is human, to recurse divine.
-L. Peter Deutsch
var req = function () {
$.ajax({
url : 'http://example.com/yourscript.php',
complete : function () {
req();
}
});
};
req();
In case it's not obvious, the above will make a new request as soon as the previous one completes, forever. You could also set a 1 second delay between requests as follows:
var req = function () {
$.ajax({
url : 'http://example.com/yourscript.php',
complete : function () {
setTimeout(function () {
req();
}, 1000);
}
});
};
req();
function doAjax(data){
$.ajax({
type: "POST",
data: data,
url: 'http://example.com/yourscript.php',
});
}
// Set interval
setInterval('doAjax()',1000);
// Set event handler
$(document).mousedown(function(){
doAjax({key: 'value'});
});
You could replace $(document) with an actual element if you don't want to capture clicks on the whole page.
You can do a lot more with the ajax function if you are looking for callbacks etc:
http://docs.jquery.com/Ajax/jQuery.ajax
//All pings you need:
ping.pushCallback(function() { YourCallback(); });
$.data(document.body, 'data_ping', ping);
//------------------------------------------------------
//Script
$.ping = function(url, options) {
this.url = url;
this.options = $.extend({
delay: 2000,
dataType: 'json',
timeout: 10000,
data: {},
callbacks: []
}, options);
this.queue();
};
$.ping.prototype = {
queue: function() { var self = this;
setTimeout(function() {
self.send();
}, self.options.delay);
},
send: function() { var self = this;
$.ajax(self.url, {
success: function(data) {
for (var i in self.options.callbacks) {
self.options.callbacks[i](data);
}
},
complete: function() {
self.queue();
},
dataType: self.options.dataType,
data: self.options.data,
type: "GET",
cache: false,
timeout: self.options.timeout
});
},
setData: function(key, value) {
this.options.data[key] = value;
},
pushCallback: function(callback) {
this.options.callbacks.push(callback);
}
};
You can put the code for pinging the server in a function, then do something like this:
setInterval('ping()',1000); //this will ping 1000 milliseconds or 1 second
You don't have to add some random extension. There are native javascript functions setInterval and setTimeout for doing stuff on set intervals. You would probably want to do something like
function ajaxPing() {
...
}
setInterval("ajaxPing()", 1000);
$(element).mousedown(ajaxPing);
On the other hand, if you really want to do the pinging every second, it would probably be sufficient to just store your data in variables on mousedown and submit it on next ping (that will happen in less than a second).

Categories