Ajax function being ignored

Asked

Viewed 53 times

1

Guys, I have this code that I’m using to search for server validations and display in the jquery validation plugin that 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, however, when I run this function it enters directly into the if’s and ends up that the return assignment within ajax is "ignored", because it happens?

1 answer

1


The variable retorno is still undefined when it passes by 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 ends, and from there 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;
    }
})
  • Opa Rafa, thanks for the reply, I will test here and give you the return ok? And merry Christmas!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.