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.
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 have an ASP.NET MVC app and I am trying to make a chain of operations, one after another using jQuery inside a javascript function. The function consists of three parts.
What I am trying to do is: If some condition is satisfied then I want to execute syncrhonous jQuery ajax call CheckData. Dependending on the result returned:
It returns ok -> I want to continue executing part2 and finally part3 in this order.
It returns Nok -> then it finishes and returns. It does not continue executing part2 and part3.
So I have set async: false but it is not working, program continues executing part2 and part3.
I know async:false is deprecated so how can I achieve this?
function onCheckValidData()
{
// do something....
// PART 1 STARTS HERE
if (some_condition_is_satified)
{
$.ajax({
url: '#Url.Action("CheckData", "MyController")',
async: false,
type: "POST",
dataType: "JSON",
beforeSend: function () {
showLoading();
},
success: function (result) {
if (!result.isOk) {
return;
}
},
complete: function(){
hideLoading();
}
});
}
// PART 2 STARTS HERE
// do something.....
// continue doing more thing.....
// more things.....
// PART 3 STARTS HERE
$.ajax({
url: '#Url.Action("MyActionMethod1", "MyController")?' + paramsStr,
type: "POST",
dataType: "html",
beforeSend: function () {
showLoading();
},
success: function (result) {
if (result == 'True') {
jsMethod2(); // jsMethod2 is another javascript method which contains another $.ajax block
}
else if (result == 'False') {
jsMethod3(); // jsMethod3 is another javascript method which contains another $.ajax block
}
else {
alert(result);
}
},
complete: function(){
hideLoading();
}
});
}
My actions in the controller:
private JsonResult CheckData()
{
MyBoolResult res = new MyBoolResult();
// do something....
return Json(new { isOk = res.isOk });
}
public String MyActionMethod1(String param1, String param2, bool param3, string param4, string param5)
{
// do something
return condition ? "True" : "False";
}
No need to make that synchornuous. If u want the "PART 2" and "PART 3" to wait for the ajax-request to finish just put them into a function and call them on success:
function onCheckValidData()
{
// do something....
// PART 1 STARTS HERE
if (some_condition_is_satified)
{
$.ajax({
url: '#Url.Action("CheckData", "MyController")',
type: "POST",
dataType: "JSON",
beforeSend: function () {
showLoading();
},
//Success will execute only if the ajax-request is finised
success: function (result) {
if (!result.isOk) {
return;
}
part2();
part3();
},
complete: function(){
hideLoading();
}
});
}
// PART 2 STARTS HERE
function part2 () {/*do something.....*/}
// PART 3 STARTS HERE
function part3 () {/*$.ajax({...})*/}
}
I'm currently looping through a number of functions that validate particular input values. One in particular requires an ajax call to validate an address. I saw that users here on SO suggested using callbacks to return the value.
The only problem is, by the time it does retrieve the value, the function had already fired within the loop and returned an undefined value. I've been searching around and wasn't sure what the best solution would be. Do I somehow delay the loop? Do I have my function setup right in the first place? Need some serious help.
var validations = [validateUsername, validatePassword, validateAddress];
function submitForm() {
var inputs = validations.map(function(validation) {
return validation();
});
return inputs.every(function(input) {
return input === true;
}); // [true, true, undefined]
}
function validateAddress() {
function addressIsValid(callback) {
$.ajax({
type: 'POST',
url: '/address/validate',
data: $form.serialize(),
dataType: 'json',
success: function(response) {
return callback(response.Data === 200);
}
});
}
function callback(response) {
return response;
}
return addressIsValid(callback);
}
You should use Promises.
First, you should make your asynchronous functions return a Promise:
function validateAddress() {
return new Promise((resolve, reject)=> {
$.ajax({
type: 'POST',
url: '/address/validate',
data: $form.serialize(),
dataType: 'json',
success: response=> {
response.Data === 200 ? resolve() : reject();
}
});
});
}
Then rewrite your submitForm function like this:
function submitForm() {
var promises = validations.map(validation=> validation());
return Promise.all(promises)
}
Then you can use submitForm like this:
submitForm()
.then(()=> {
// form is valid
}, ()=> {
// form is invalid
})
In my event handler function I need to check if some field is unique. To achieve this I use ajax call to the function in back end.
From that function data is send back using callback.
at this moment I have Event handler:
self.searchKeyboardCmd = function (data, event) {
if (event.keyCode == 13) {
foo(function (callback) {
if(!callback){
return false // Returning only from this method. Not parent method
}
});
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' });
self.Test("");
return false;
}
return true;
};
In which in lines:
foo(function (callback) {
alert(callback);
});
I call this method with ajax call:
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);
}
});
}
At this moment correct data is received by foo in main method. But I need to make searchKeyboardCmd aware of the value of the callback value from Ajax call. I read in my other question that I need to make searchKeyboardCmd accepting callback from foo call.
Please do net send me to the question How do I return the response from an asynchronous call?. I'm reading that topic all day and still got nothing
What if you put all the code that depends on the callback return into the callback?
foo(function (callback) {
if(callback) { // Changed this condition
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' });
self.Test("");
}
});
Just an idea - this is jQuery way. This is your function:
function foo(callback) {
return $.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);
}
});
}
$.ajax - returned a Defered object.
This is modified searchKeyboardCmd function:
self.searchKeyboardCmd = function (data, event) {
var dfd = $.Deferred();
if (event.keyCode == 13) {
foo(callback).done(
function() {
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' });
self.Test("");
dfd.resolve();
}
);
}
dfd.reject();
};
This code is untested. When you write JavaScript you must thing asynchronously. If you provide working jsFiddle with your solution I can help you more.
Best regards.
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;
}