Javascript function returning Undefined

Asked

Viewed 2,877 times

2

I’m having a problem with a Javascript function. I need to verify the existence of an item in the database and so use a js function with ajax call verificaExistente. php returns me a Json and in this function I check if there are elements in that return. The bank’s return is happening as predicted, the problem is the return. When I call this function within the onclick of the save button, the value returned is undefined. Has anyone ever had a similar mistake? I appreciate 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;
        }
    });
}
  • Yes. The return retorno in the success of $.Ajax() comes normal. I checked with a console.log and the verification value is actually zero.

3 answers

3


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

The correct one 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 stream would be to do this server-side check 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 success message via ajax.

  • I could understand the reasoning, but the return true or return false would not check the if work?

  • Like I said, he’s not returning anything, I’ll edit to make this part of the explanation better...

  • 1

    Puts. It worked cool. I thought the return false and return true within the success would be transferred to my function. Thanks to the help @Felipe Avelar.

1

You must note that an AJAX call is asynchronous and the result you want will appear within the Success function. When you run the function verificaExistente it will start AJAX which 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
    });
}

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

0

One way would be to create another method and pass the value to it within the "Success", and so 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 that this is not good practice.

Browser other questions tagged

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