The else block gets executed always before validating the if condition. The proceedToNextValidation() executed before the Validation(clusterId) gets fully completed its execution. How to wait for the function Validation(clusterId) to be executed fully and then based on its result evaluate the if-else block.
function validateUpgradateStatus()
{
var target = $("#selectcluster").data("ejDropDownList");
var clusterId = target.model.itemValue;
var isValidated = Validation(clusterId);
if(isValidated )
Error("error msg");
else
proceedToNextValidation();
}
function Validation(id) {
$.ajax({
type: "POST",
url: '@Url.Action("Method", "Controller")',
data: {
clusterId: id,
},
success: function (response) {
if (response.isSdkUpgrading) {
return true;
}
else {
return false;
}
}
});
}
Your logic is aimed towards Javascript being a synchronous language. Unfortunately, you have fallen for the same trap as I and many others have when first developing in a language like Javascript.
So your Validation() function sends an AJAX request, and then ON SUCCESS (aka: the HTTP request completed successfully), your ANONYMOUS SUCCESS CALLBACK FUNCTION returns true or false depending on the result. The key here is that the Validation() function is not returning true or false in the same way. Immediately, the Validation function actually returns 'null'. It doesn't wait for the AJAX (HTTP) request to complete.
The fix here is that you need to:
Option #1: Pass Validation a 2nd parameter called callback, which is a function. You then set the success AJAX property to your parameter callback as so:
var callback = function(response){
if(response.isSdkUpgrading)Error("error msg");
else proceedToNextValidation();
}
function Validation(id, callback){
$.ajax({
type: "POST",
url: '@Url.Action("Method", "Controller")',
data: {clusterId: id},
success: callback
});
}
Option #2: Move your logic that needs to wait for the AJAX (HTTP) request to complete into your anonymous success callback as so:
function Validation(id){
$.ajax({
type: "POST",
url: '@Url.Action("Method", "Controller")',
data: {clusterId: id,},
success: function(response){
if(response.isSdkUpgrading)Error("error msg");
else proceedToNextValidation();
}
});
}
Hope this helps.
You should ideally place your code inside the callback then...
function validateUpgradateStatus()
{
var target = $("#selectcluster").data("ejDropDownList");
var clusterId = target.model.itemValue;
Validation(clusterId);
}
function Validation(id) {
$.ajax({
type: "POST",
url: '@Url.Action("Method", "Controller")',
data: {
clusterId: id,
},
success: function (response) {
if (response.isSdkUpgrading) {
Error("error msg");
}
else {
proceedToNextValidation();
}
}
});
}
if(!isValidated)
Error("error msg");
else
proceedToNextValidation();
If ! not Validated then you will get the error, Else proceedToNextValidation();