Ajax function being ignored

1

Well, I have this code that I'm using to get the server validations and display in the jquery validation plugin I use.

function nomeExiste(value, validator, $field) {                         
    var retorno;            
    $.ajax({
        url: '/saboia/funcionarios/'+$field.val()+'/validaNovo/',
        method: 'PUT',                              
        success: function(e){   
            console.log(e);
            retorno = e;           
        }
    });                                                     

    if (!retorno) {
        return false;
    }else{
        return true;
    }
}

The return of this function comes from the server and is a Boolean, but when I execute this function it goes directly to the if's and it ends up that the return assignment inside ajax is "ignored", why does it happen? >     

asked by anonymous 23.12.2016 / 03:31

1 answer

1

The variable retorno is still undefined when it passes if . This is because the script does not wait for the Ajax request to finish to continue.

You need to put a callback function to be called as soon as the request is finished, and then continue with your script.

function nomeExiste(value, validator, $field, callback) {
    $.ajax({
        url: '/saboia/funcionarios/' + $field.val() + '/validaNovo/',
        method: 'PUT',
        success: function(e) {
            console.log(e);
            callback(e);
        }
    });
}

nomeExiste("value", "validator", "$field", function(e) {
    if (e) {
        return true;
    } else {
        return false;
    }
})
    
23.12.2016 / 04:35