I have this code :
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
});
I want if data == 0 need to make another call on app_auction_end after 10 sec. Can you help me please ? Thx in advance and sorry for my english
Give the operation a named function:
var someFunction = function () {
$.ajax({
//...
});
};
Which you would then use for your .on() call:
.on('finish.countdown', someFunction)
And in the success handler, set a timeout for that function:
if (data == 0) {
setTimeout(someFunction, i_timer);
}
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
//do our initial call otherwise it will never get called.
onEndAuction();
});
Related
I have made a function that is controlling a row in a my database for a certain number with AJAX.
Im calling the function with a click function and putting the function in a setInterval function to make the check 10 times a second.
In the beginning it will return 0, but at some point (usually within 5 seconds) it will return something els than 0, when it does i want to clearInterval.
But im not sure how to this?
This is my function:
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
var buzzer = setInterval("get_buzzer()",100);
});
});
You can do something like
$(document).ready(function () {
//make buzzer a share variable
var buzzer;
$('#test').click(function () {
buzzer = setInterval(get_buzzer, 100);
});
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}
});
}
});
Try this : declare global variable to store interval and call window.clearInterval in success call of ajax
var buzzer;
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
//clear interval
window.clearInterval(buzzer);
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
buzzer = setInterval("get_buzzer()",100);
});
});
Use:
inside success use: And make var buzzer Gloval var.
clearInterval(buzzer);
Refence
You just need to clear the interval in the success handler of ajax call over a condition.
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
(14 answers)
Closed 9 years ago.
How do I make function out of this?
//check if station is alive
$.ajax({
url: "lib/grab.php",
data: "check_live=1&stream_url="+valueSelected,
type: "GET",
success: function (resp) {
if (resp == 1) {
play_this(valueSelected);
} else {
//
}
},
error: function (e) {
console.dir(e);
}
});
I thought I could do something like this:
function is_alive(valueSelected) {
result = false;
//check if station is alive
$.ajax({
url: "lib/grab.php",
data: "check_live=1&stream_url="+valueSelected,
type: "GET",
success: function (resp) {
if (resp == 1) {
result = true;
} else {
//
}
},
error: function (e) {
console.dir(e);
}
});
return result;
}
But obviously due to asynchronous nature of ajax call, result always returns false.
What is the trick of dealing with this situation?
Seems to work:
//check if station is alive
function is_alive(url) {
//
var result = false;
//
return $.ajax({
url: "lib/grab.php",
data: "check_live=1&stream_url="+url,
type: "GET",
success: function (resp) {
if (resp == 1) {
//
result = true;
//
}
},
error: function (e) {
console.dir(e);
}
}).then(function() {
return $.Deferred(function(def) {
def.resolveWith({},[result,url]);
}).promise();
});
}
And call it like this:
//Change song on select, works both for fav and station lists
$(document).on("click", ".ui-listview li a", function(){
var valueSelected = $(this).data("station-url");
//
is_alive(valueSelected).done(function(result,url){
if (result) {
//
play_this(valueSelected);
//
}
});
});
You don't have to make it synchronous to make it a useful function.
function is_alive(valueSelected) {
//check if station is alive
return $.ajax({
url: "lib/grab.php",
data: "check_live=1&stream_url=" + valueSelected,
type: "GET",
error: function (e) {
console.dir(e);
}
});
}
is_alive(somevalue).then(function(result){
console.log(result, somevalue);
});
You can supply the async: false option
function is_alive(valueSelected) {
result = false;
//check if station is alive
$.ajax({
async: false,
url: "lib/grab.php",
data: "check_live=1&stream_url="+valueSelected,
type: "GET",
success: function (resp) {
if (resp == 1) {
result = true;
} else {
//
}
},
error: function (e) {
console.dir(e);
}
});
return result;
}
I'm trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn't work. Just the first time works fine, then return false..
$('#do-login').click(function(e) {
e.preventDefault();
if ( $(this).data('requestRunning') ) {
return;
}
$(this).data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
});
Any ideas? Thanks!
The problem is here:
complete: function() {
$(this).data('requestRunning', false);
}
this no longer points to the button.
$('#do-login').click(function(e) {
var me = $(this);
e.preventDefault();
if ( me.data('requestRunning') ) {
return;
}
me.data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
me.data('requestRunning', false);
}
});
});
Use on() and off(), that's what they are there for :
$('#do-login').on('click', login);
function login(e) {
e.preventDefault();
var that = $(this);
that.off('click'); // remove handler
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize()
}).done(function(msg) {
// do stuff
}).always(function() {
that.on('click', login); // add handler back after ajax
});
});
In your ajax callbacks the context (this) changes from the outer function, you can set it to be the same by using the context property in $.ajax
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this, //<-----
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
You can disable the button.
$(this).prop('disabled', true);
I have also faced a similar problem.
Just adding $('#do-login').attr("disabled", true); gives me the solution.
$('#do-login').click(function(e) {
e.preventDefault();
$('#do-login').attr("disabled", true);
.........
.........
Here do-login is button id.
I've tried this and worked very fine for me, I was having trouble that $.ajax send more request until results return,
var settings = {
"url": "/php/auth/login.php",
"method": "POST",
"timeout": 0,
"async": false,
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"data": jsondata, //data pass here is in JSON format
};
$.ajax(settings).done(function (ress) {
try{
console.log(ress, "Result from Ajax here");
}
catch(error){
alert(error);
console.log(ress);
}
});
async : false worked for me.
Thanks.
Or you can do it by $(this).addClass("disabled"); to you button or link and after click is performed, you can $(this).removeClass("disabled");.
// CSS
.disabled{
cursor: not-allowed;
}
// JQUERY
$('#do-login').click(function(e) {
e.preventDefault();
$(this).addClass("disabled");
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this,
success: function(msg) {
//do more here
$(this).removeClass("disabled");
},
});
});
P.S. If you use bootstrap css, you do not need the css part.
I found the approach useful. I've implemented it as a general purpose function for jQuery with ES6.
export default function (button, promise) {
const $button = $(button);
const semaphore = 'requestRunning';
if ($button.data(semaphore)) return null;
$button.data(semaphore, true);
return promise().always(() => {
$button.data(semaphore, false);
});
}
Because $.ajax() returns a promise, you simply pass in the promise and the function takes care of the rest.
Roughly speaking, here's the usage.
import preventDoubleClick from './preventdoubleclick';
...
button.click(() => {
preventDoubleClick(this, () => $.ajax()
.done(() => { console.log("success") }));
});
This function can help you with control multi Ajax requests and it's has timeout function which can return flag status to 0 after ex. 10sec (In case the server took more than 10 seconds to respond)
var Request_Controller = function(Request_Name = '', Reactivate_Timeout = 10000)
{
var a = this;
a.Start_Request = function(){
if(window.Requests == undefined){
window.Requests = {};
}
window.Requests[Request_Name] = {'Status' : 1, 'Time': + new Date()};
}
a.End_Request = function(){
if(window.Requests == undefined){
window.Requests = [];
}
window.Requests[Request_Name] = undefined;
}
a.Is_Request_Running = function(){
if(window.Requests == undefined || window.Requests[Request_Name] == undefined){
return 0;
}else{
var Time = + new Date();
// Reactivate the request flag if server take more than 10 sec to respond
if(window.Requests[Request_Name]['Time'] < (Time - Reactivate_Timeout))
{
return 0;
}else{
return 1
}
}
}
}
To use it:
var Request_Flag = new Request_Controller('Your_Request_Name');
if(!Request_Flag.Is_Request_Running()){
Request_Flag.Start_Request();
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
Request_Flag.End_Request();
}
});
}
for prevent multiple ajax request in whole site. For example: If use ajax request in other ajax page, Using ajax in php loop, etc, Give you multiple ajax request with one result. I have solution:
Use window.onload = function() { ... }
instead of
$(document).ready(function(){ ... });
on the main index.php page. Its will be prevent all multi request. :)
First of all i am not good enough in js.
I have two function in a page and i have to call another function in an existing function.
I have=>
function suggest1(inputString){
if(inputString.length == 0) {
$('#suggestions1').fadeOut();
}
else{
$('#p_name').addClass('load');
$.post("autosuggest.php", {queryString: ""+inputString+""}, function(data)
{
if(data.length >0)
{
$('#suggestions1').fadeIn();
$('#suggestionsList1').html(data);
$('#p_name').removeClass('load');
}
});
}
}
function fill1(thisValue) {
$('#p_name').val(thisValue);
$('#p_nameA').val(thisValue);
setTimeout("$('#suggestions1').fadeOut();", 100);
}
This is an auto suggest function
Ineed to call function which is bellow, which can use the value of $('#p_name').val(thisValue); in var name_tast. Is it possible or not?
function getAccaounce()
{
var name_tast = document.getElementById("p_nameA").value;
$.ajax({
type: "POST",
url: 'ajax_accaounce.php',
dataType: 'json',
data: {
'p_nameA': name_tast,
},
success: function(data)
{
$('#available1').html(data.message1);
$('#price1').html(data.message2);
}
});
}
Thanks in advance.
I want to repeatedly count time and update the current time every one minute. My code doesn't work. Firebug console says the final line function getStatus() is not defined. How to call this function repeatedly?
jQuery(document).ready(function($){
$(function() {
getStatus();
});
function getStatus() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url : ajaxurl,
data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
success: function(response) {
if(response == "false") {
alert("failed")
}
else {
$("#message").html(response)
}
}
});
setTimeout("getStatus()",60000);
}
},(jQuery));
your issue is getStatus is wrapped in another callback. either do window.getStatus = function(){}, or turn your code to this:
jQuery(document).ready(function($){
var getStatus = function() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url : ajaxurl,
data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
success: function(response) {
if(response == "false") {
alert("failed")
}
else {
$("#message").html(response)
}
}
});
setTimeout(getStatus,60000);
};
$(function() {
getStatus();
});
},(jQuery));
Passing a string to setTimeout will make it eval the string, which you should avoid, and generally not required by your code
You could use setInterval(getStatus, 60000) instead perhaps, but otherwise you should use setTimeout(getStatus, 60000). Do not use a string as the function callback but rather the named function.
Use setInterval(function, milliseconds)
jQuery(document).ready(function ($) {
var getStatus = function() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url: ajaxurl,
data: {
action: "update_edit_lock",
post_id: post_id,
nonce: nonce
},
success: function (response) {
if (response == "false") {
alert("failed")
} else {
$("#message").html(response)
}
}
});
}
setInterval(getStatus, 1000);
}, (jQuery));