JavaScript function returning Undefined

2

I'm having a problem with a JavaScript function. I need to check the existence of an item in the database and so I use a js function with ajax called verificaExistente . The php returns me a Json and in this function I check if there are elements in that return. Bank payback is going as planned, the problem is return . When I call this function inside the% button of the save button, the value returned is onclick . Has anyone ever had a similar error? Thanks for the help.

Below the code:

$( "#btnSalvar" ).on( 'click', function(){            
    if( $( "#frmDados" ).valid() !== false ){
        if(verificaExistente()) salvar();
        else alert("Dados já existentes");            
    }
});

function verificaExistente(){        
    $.ajax({
        url: "verificaItem.php",
        type: 'POST',
        dataType: 'json',
        cache: false,
        data:{ 
            id_tabela          : $("#id_tabela").val(),
            id_revestimento    : $("#id_revestimento").val(),
            operador           : 'AND'
        },
        error: function(){
            alert('Erro ao Tentar ação.');
        },
        success: function( retorno ){ 
            if(retorno.dados.length > 0) return false;
            return true;
        }
    });
}
    
asked by anonymous 12.03.2015 / 13:43

3 answers

3

What is happening is that you are getting the return of the verificaExistente function, and since it returns nothing, the result is undefined . What is returning true / false is the function associated with success of ajax and not verificaExistente . However, the click function does not receive the return from success, but from the existing check function, which, as explained above, will always return undefined.

The correct would be to check if it exists and only then call a return function, as in the following example:

$( "#btnSalvar" ).on( 'click', function(){            
    if( $( "#frmDados" ).valid() !== false ){
        verificaExistente()
    }
});

function verificaExistente(){        
    $.ajax({
        url: "verificaItem.php",
        type: 'POST',
        dataType: 'json',
        cache: false,
        data:{ 
            id_tabela          : $("#id_tabela").val(),
            id_revestimento    : $("#id_revestimento").val(),
            operador           : 'AND'
        },
        error: function(){
            alert('Erro ao Tentar ação.');
        },
        success: function( retorno ){ 
            if(retorno.dados.length > 0) alert("Dados já existentes");
            else salvar();                
        }
    });
}

However, the correct flow would be to do this server-side verification only using PHP or the technology you are using to do this validation and only return an error if the data already exists or a message succeeds through ajax .

    
12.03.2015 / 13:49
1

You have to take into account that an AJAX call is asynchronous and the result you want will appear inside the success function. When you run the verificaExistente function it will start the AJAX that will run parallel and finish the function without waiting for ajax.

What I suggest is to make a callback. For example:

$( "#btnSalvar" ).on( 'click', function(){            
    if( $( "#frmDados" ).valid() !== false ){
        verificaExistente(function(retorno ){
             if(retorno.dados.length > 0) return alert("Dados já existentes");
             salvar();
        });
    }
});

function verificaExistente(fn){        
    $.ajax({
        url: "verificaItem.php",
        type: 'POST',
        dataType: 'json',
        cache: false,
        data:{ 
            id_tabela          : $("#id_tabela").val(),
            id_revestimento    : $("#id_revestimento").val(),
            operador           : 'AND'
        },
        error: function(){
            alert('Erro ao Tentar ação.');
        },
        success: fn // usa a callback aqui
    });
}

In this way you pass the function and what you want to do for the AJAX response, which will be executed when the server responds.

    
12.03.2015 / 14:08
0

One way would be to create another method and pass the value to it within "success", and thus have what you want.

Example:

$.ajax({
    url : site,
    type : 'GET',
    success : function(x) {
    //Faz algo  
    metodoX(valor); //Aqui você chama outro método e passa o valor retornado do ajax.
    }
});

function metodoX(valor){
console.log(valor);
}

Remembering this is not a good practice.

    
10.05.2016 / 15:44