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;
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 months ago.
this code doesn't work, because it always return undefined. In my opinion the "success" from the ajax should return, if the result is there.
How to make sure, that the boolean will be returned?
<script>
$('#sbtn').on("click", function(e) {
e.preventDefault();
// if user exists, set validated to true
var validated = checkUser('requestedUser');
// if the user is validated, submit form
if(validated) {
//alert("Thank You");
$('#setup').submit();
}
}
function checkUser(user) {
data = {
lernsax_email: user
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: data,
success: function(msg){
if(msg === "passed") {
// php returns "passed", if the user can be found
console.log(msg);
return true;
} else {
console.log(msg);
return false;
}
},
});
}
</script>
you can use Promise
<script>
$('#sbtn').on("click", function(e) {
e.preventDefault();
// if user exists, set validated to true
let result = checkUser('requestedUser');
result.then(validated => {
if(validated) {
//alert("Thank You");
$('#setup').submit();
}
});
}
function checkUser(user) {
data = {
lernsax_email: user
}
return new Promise(resolve => {
$.ajax({
type: "POST",
url: "checkuser.php",
data: data,
success: function(msg){
if(msg === "passed") {
// php returns "passed", if the user can be found
console.log(msg);
resolve(true);
} else {
console.log(msg);
resolve(false);
}
},
});
});
}
</script>
or move
if(validated) {
//alert("Thank You");
$('#setup').submit();
}
to success funtion of ajax
<script>
$('#sbtn').on("click", function(e) {
e.preventDefault();
// if user exists, set validated to true
checkUser('requestedUser');
}
function checkUser(user) {
data = {
lernsax_email: user
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: data,
success: function(msg){
if(msg === "passed") {
// php returns "passed", if the user can be found
console.log(msg);
$('#setup').submit();
return true;
} else {
console.log(msg);
return false;
}
},
});
}
</script>
I am doing a few recurring AJAX calls where I pass an array from the front-end to the back-end and whenever it comes back to the front-end, the array gets smaller (by 1) and ultimately it'll be empty, therefore my recursive calls will stop.
Here's my calls:
function download_required_files(demo_data) {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
return false;
}
if(data.can_continue !== 'yes') {
return false;
}
if(data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
download_required_files(demo_data);
}
$('.demo-loader-content').fadeOut();
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
Assuming I have 2 steps to download files for, this download_required_files will run twice, then it'll be done, but if I do:
var download_process = download_required_files(demo_data) //Runs 2 times
download_process.done(function() { //Do stuff here once that function ran 2 times });
It gives me the: Cannot read property 'done' of undefined error and for good reason. That download_process is not a promise object for it to have that property, it's just...empty.
Where should I intervene in my download_required_files so that it signals to outside code that "Hey, in a promise environment, I'm done!"?
Although the result of the call to $.ajax is a jqXHR object, which is promise-like, for what you describe I think I'd go with your own native Promise (or Deferred if you prefer) to represent the overall recursive process:
function download_required_files(demo_data) {
return new Promise(function(resolve, reject) {
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `reject` instead of `resolve` below.
$('.demo-loader-content').fadeOut();
resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
});
}
Or using Deferred instead:
function download_required_files(demo_data) {
var d = $.Deferred();
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
d.resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `d.reject` instead of `d.resolve` below.
$('.demo-loader-content').fadeOut();
d.resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
return d.promise();
}
This would be my approach, separating the individual AJAX requests from the looping over the content, and that also from the DOM updates:
function download_one_file(demo_data) {
return jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: setup_page_params.ajax_nonce,
content_install_request_data: JSON.stringify(demo_data),
}
});
}
function download_loop(demo_data) {
return download_one_file(demo_data).then(function(data) {
if (!data) {
return Promise.reject();
} else if (data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
return download_loop(demo_data);
} else {
return Promise.resolve();
}
});
}
function download_required_files(demo_data) {
return download_loop(demo_data).finally(function() {
$('.demo-loader-content').fadeOut();
});
}
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();
});
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)
Closed 8 years ago.
I have a function searchKeyboardCmd which is binded as an event handler to the textbox.
Its purpose is to check the data in that textbox is unique. If no it should break execution of this handler and show alert window. If unique it should get data from other texboxes and store it in array ( code fragment from line `var a=new ())
self.searchKeyboardCmd = function (data, event) {
if (event.keyCode == 13) { //checking if enter was pressed or other key
foo(function (result) {
if (result == 'false') {
alert("Numer seryjny nie jest unikalny");
return true;
}
});
var a = new Eq();
a.StorageId(self.StorageTemp());
a.StartDate(self.StartDateTemp());
a.DeviceSerialNumber(self.Test());
a.DeviceId(self.DeviceTemp());
a.Issue(self.Issue())
a.IssueDesc(self.IssueDesc());
a.Quantity(self.number());
a.Project(self.Project());
a.MeUser(self.MeUser());
self.data.push(a);
$('.datepicker').datepicker({ autoclose: true, todayHighlight: true/*, language: "pl"*/, format: 'dd/mm/yyyy' });
deviceIdField.focus();
self.Test("");
return false;
}
return true;
};
My foo function which call back end method. It receives as true from it if unique. False other ways.
function foo(callback) {
$.ajax({
url: "/DeviceInstance/IsUnique",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: JSON.stringify({ value: viewModel.Test() }),
error: function (data) {
alert("Dodanie nie powiodło się " + data);
},
success: function (data) {
callback(data);
}
});
So my problem is in breaking execution of my main event handler method.
I tried modifying this lines:
self.searchKeyboardCmd = function (data, event,callback)
and
foo(function (result) {
console.log(result);
callback(result);
});
The only response I'm getting is : undefined is not a function
Try this:
var f = foo(function (result) {
if (result == 'false') {
alert("Numer seryjny nie jest unikalny");
return true;
}
});
if(!f){
return; // (Or return true or false)
}
If f() returns false, the code below the function call won't be executed, if it returns true, it will be.