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();
Related
I need for help in fat free
I want to use ajax to render to a specific route every 5 seconds
But I can't console any data the ajax page
and this is my php code :
elseif ($this->session->isRole(UserRole::TRAINEE)) {
$this->assets->addJs('meeting.js');
$f3->push('init.js', 'Meetings');
$f3->set('name', $name);
$f3->set('joinUrl', 'meeting/' . $meetingId);
$this->render();
}
and this is my ajax code
let Meetings = function () {
let joinMeeting = function () {
$(document).on('click', '.join-meeting', function (e) {
e.preventDefault();
let meetingId = data.meeting_id;
$.ajax({
type: 'GET',
url: '/meeting/' + meetingId,
contentType: 'application/json',
success: function (result) {
if (result.joinUrl === 'none') {
noty({text: 'Could not join the requested meeting.', type: 'error'});
} else {
setInterval(window.open(result.joinUrl, '_blank'), 5000);
}
},
error: function (jqXHR) {
noty({text: 'Application error', type: 'error'});
}
});
});
};
return {
//main function to initiate the module
init: function () {
joinMeeting();
}
}
}();
If you render a page, the page is loaded and the script is reloaded again and set interval is never ejecuted.
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.
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
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 years ago.
Trying to run a script, (test.al();) and inside test.al, its called getcrypt.php();, the php script is on a webserver, and it is working. Currently, these are my scripts
JS
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
return v;
}
});
}
}
var test = {
al: function () {
a = getcrypt.php();
alert(a);
}
}
PHP
<?php
$id = $_POST['id'];
if ('getit' == $id){
$value = 'VALUE';
echo $value;
}else{
echo 0;
}
?>
In this way, it will show an alert with 'unidefined', and if i add a alert(v); right before return v, it will show me 'VALUE', but not able to use it outside the variable...
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
return v;
}
});
}
}
This will give me an alert with the correct value (AFTER THE 'undefined')
This is because of the asynchronous call you're making. The return is only for the success function and not for the php function.
To get the value out you would need to write:
var value;
var getcrypt = {
php: function (callback) {
$.ajax({
url: "",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
callback(v);
}
});
}
}
getcrypt.php(function(v) {
alert(v);
// This happens later than the below
value = v;
});
// The below will still not work since execution has already passed this place
// alert will still return undefined
alert(value);
The problem is jQuery ajax works with callbacks and does not work with return value's so you need to add an callback to your getcrypt function so say
var getcrypt = {
php: function (callback) {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
callback(v);
}
});
}
}
so now if you call
getcrypt.php(function(returnVar){
alert(returnVar)
});
you will get an alert with VALUE
$.ajax returns immidiately (well, almost :)) upon calling, before the response is received. You should rewrite your code to accomodate to this fact, something like this;
var getcrypt = {
php: function(){
$.ajax({
//..other params ..//
success: function(msg){
var v = msg.match(/^.*$/m)[0];
alertResponse(v);
}
});
},
alertResponse: function(processedResponse) {
alert(v);
}
}
var test = {
al: function(){
getcrypt.php();
}
}
If you need your response in test object, you move alertResponse to that object and call it from success method. I think this tutorial might be useful for you to learn javascript event-driven programming model.
$.ajax calls are async. So what you get is the return value of $.ajax (when the request is sent, before a response is received). It is only when the browser receives a response to the ajax call that the success callback is run, as a seerate process from the $.ajax call. In other words the return value of $.ajax will always be null. I'm not sure it's possible to do anythging with the return value of the success callback, you need to put your logic (or a call to another function with the logic) in the success callback itself, in the same way you did with the alert in your final example
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Kill Ajax requests using JavaScript using jQuery
Here is the simple code I am working with:
$("#friend_search").keyup(function() {
if($(this).val().length > 0) {
obtainFriendlist($(this).val());
} else {
obtainFriendlist("");
}
});
function obtainFriendlist(strseg) {
$.ajax({
type: "GET",
url: "getFriendlist.php",
data: "search="+strseg,
success: function(msg){
UIDisplayFriends(msg);
}
});
}
Essentially, if a keyup event is fired before the function obtainFriendlist returns a result (and triggers UIDisplayFriends(msg), I need to cancel the in-flight request. The issue I have been having is that they build up, and then suddenly the function UIDisplayFriends is fired repeatedly.
Thank you very much, and advice is helpful too
The return value of $.ajax is an XHR object that you can call actions on. To abort the function you would do something like:
var xhr = $.ajax(...)
...
xhr.abort()
It may be smart to add some debouncing as well to ease the load on the server. The following will only send an XHR call only after the user has stopped typing for 100ms.
var delay = 100,
handle = null;
$("#friend_search").keyup(function() {
var that = this;
clearTimeout(handle);
handle = setTimeout(function() {
if($(that).val().length > 0) {
obtainFriendlist($(that).val());
} else {
obtainFriendlist("");
}
}, delay);
});
A third thing that you should really be doing is filtering the XHR responses based on whether or not the request is still valid:
var lastXHR, lastStrseg;
function obtainFriendlist(strseg) {
// Kill the last XHR request if it still exists.
lastXHR && lastXHR.abort && lastXHR.abort();
lastStrseg = strseg;
lastXHR = $.ajax({
type: "GET",
url: "getFriendlist.php",
data: "search="+strseg,
success: function(msg){
// Only display friends if the search is the last search.
if(lastStrseg == strseg)
UIDisplayFriends(msg);
}
});
}
How about using a variable, say isLoading, that you set to true through using the beforeSend(jqXHR, settings) option for .ajax, and then using the complete setting to set the variable back to false. Then you just validate against that variable before you trigger another ajax call?
var isLoading = false;
$("#friend_search").keyup(function() {
if (!isLoading) {
if($(this).val().length > 0) {
obtainFriendlist($(this).val());
} else {
obtainFriendlist("");
}
}
});
function obtainFriendlist(strseg) {
$.ajax({
type: "GET",
url: "getFriendlist.php",
beforeSend: function () { isLoading = true; },
data: "search="+strseg,
success: function(msg){
UIDisplayFriends(msg);
},
complete: function() { isLoading = false; }
});
}