I have a function called getData which makes an ajax request. I want to use this ajax request result on my form submission for validation along with other validation. Since ajax is asynchronous i am calling a callback function inside my success function.
Now i want to assign the callback function value to a javascript variable for my form validation. I have tried using jquery validation submit handler method but that doesnt work either. My callback function is returning the desired output, but when i try to console.log the variable i have assigned it too, it returns undefined
Here is my code
function getData(cb){
$.ajax({
url:'/stops/reason_valid',
method: 'get',
dataType: "json",
success: function(data) {
if(data.reason == '6'){
if(($('.search_of_item1').is(':checked')) || ($('.search_of_item2').is(':checked'))){
$(".searchValidError").hide();
cb(false);
}
else{
$(".searchValidError").show();
cb(true);
}
}
}
})
}
$(".actionstaken_submit").click(function(e){
var validationFailed = false;
var searchValidation = getData(function(cb){
alert(cb);
return cb;
});
console.log(searchValidation);
if($('.no_validation').is(":checked")){
if($('.action_validation:checked').length > 1){
$('.noneError').show();
validationFailed = true;
}
else{
$('.noneError').hide();
validationFailed = validationFailed || false;
}
}
if (validationFailed || searchValidation) {
e.preventDefault();
return false;
}
});
Note: if i do alert(cb)
display's the appropriate value but console.log(searchValidation)
returns undefined