add callback to function with ajax call
I have a function that is called on an element's blur. In there I have an if statement checking the return statement of a function. Well in the function, I am making an ajax call. I have been reading that this will not work because the function will return false before the ajax is done. So I read something about needing to use a callback, but I didn't fully understand it. Can someone help me figure out how to refactor my code so it will work correctly?
First blur function:
- $("#OrderItem_itemQty").blur(function () {
$("#messageBar").html("adding item...").slideDown('slow');
if (checkValidInput()) {
console.log("valid");
@*$("#messageBar").html("Updating table...");
if(!$("#messageBar").is(':visible')){
$("#messageBar").slideDown('slow');
}
$.ajax({
url: '@Url.Action("_AddItem", "OrderEntry")',
data: $("#myForm").serialize(),
type: 'POST',
success: function (html) {
$("#items").html(html);
if ($("#messageBar").is(':visible')) {
$("#messageBar").slideUp('slow');
}
$("#messageBar").html("");
}
});*@
}
else {
console.log("invalid");
}
});
And the checkValidInput() function:
- function checkValidInput() {
if ($.trim($("#OrderItem_ImId").val())) {
if ($.trim($("#OrderItem_itemQty").val())) {
$.ajax({
url: '@Url.Action("CheckValidIMID","OrderEntry")',
type: 'POST',
data: { IMID: $("#OrderItem_ImId").val() },
success: function (result) {
if (result == "true") {
console.log("its true!!");
return true;
} else {
$("#OrderItem_ImId").select();
$("#messageBar").html("imid not found");
console.log("its false1!!");
return false;
}
}
});
}
else {
$("#OrderItem_itemQty").focus();
$("#messageBar").html("Please fill in the quantity");
console.log("its false2!!");
return false;
}
}
else {
$("#OrderItem_ImId").focus();
$("#messageBar").html("Please fill in the imid");
console.log("its false3!!");
return false;
}
}
checkValidInput does return true, but only after returning false.