0

I'm trying to validate a field by making an ajax call. However because it is an async call it is always returning false. Ive tried to add a timeout but still no luck. Am I doing something wrong? I also tried it using a simple check to see if the ajax call was the issue and it worked fine.

     $.validator.addMethod("validateSupplierCode" + currTabExt, function (value, element, params) {
        var result = false;
        callAjax('Supplier/ValidateSupplier?Code=' + value, 'GET', "", function success(data) {
            if (data.isValid) {
                console.log("trueee");
                result = true;
            } else {
                console.log("falsseeeee");
                result = false;
            }
        });
        setTimeout(function () {
                return result;           
        }, 100);
    }, "Please enter a valid supplier or 'MISC'");
zayn94
  • 65
  • 1
  • 11

2 Answers2

-1

I think your "return" statement should be inside the callback function of your AJAX call. Something like this :

$.validator.addMethod("validateSupplierCode" + currTabExt, function (value, element, params) {
    var result = false;
    callAjax('Supplier/ValidateSupplier?Code=' + value, 'GET', "", function success(data) {
        if (data.isValid) {
            console.log("trueee");
            result = true;
            return result;
        } else {
            console.log("falsseeeee");
            result = false;
            return result;
        }
    });
}, "Please enter a valid supplier or 'MISC'");
Yesub
  • 437
  • 6
  • 17
  • I tried that first however it did not work. I checked forums and it said to try using timeouts – zayn94 Mar 27 '18 at 09:18
-1

Your ajax call is Aysnc, you need to hit sync call if you want to return through ajax call in sync way

Understand this function and implement logic in your ajax call Btw only thing that you need to update in your ajax call is that async : false

function syncMethod() {
    var returnValue= false;
    $.ajax({
    async: false,
    url: "url",
    success: function() {
         returnValue= true;
    },error:function(){
         returnValue= false;
    }});

    return returnValue;
}
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29