Working with the return result of an ajax request with jquery

Asked

Viewed 1,113 times

2

I wonder if it is possible to compare a value returned from an Ajax function with an external variable using jquery.

When I try to make the comparison I realize that the external variable is not recognized within the function of Ajax.

How can I make this check as follows the example?

    $(document).ready(funcntion(e){
    var variavel = 123; //define um valor
    //busca um valor para a comparação
    $.ajax({
        url:'script.php',
        type:'post',
        dataType:'json',
        success: function(result){
            //verifica se retornou um objeto
            if(typeof(result) == 'object') {
                //separa o valor retornado
                var num = result[0];
                //comparar o valor retornado com a variável declarada           
                    if(num == variavel){
                        alert('o valor é igual');
                    }else{
                        alert('o valor é diferente');
                    }
                }
            }
        });
    }

1 answer

0


Function in the first line is spelled wrong. Forgot the last parentheses and point and comma to close the .ready().

In addition, it is likely that your num is not receiving the result, because I noticed that you are trying to receive an object but you are passing the value as if it were an array. The best way to check this is by putting a console.log(result) shortly after the if to see how the result arrives in the application

   $(document).ready(function(e){
    var variavel = 123; //define um valor
    //busca um valor para a comparação
    $.ajax({
        url:'script.php',
        type:'post',
        dataType:'json',
        success: function(result){
            //verifica se retornou um objeto
            if(typeof(result) == 'object') {
                console.log(result);
                var num = result[0]; // veja o formato com que o result chega se for objeto passe como var num = result.campo;
                //comparar o valor retornado com a variável declarada           
                    if(num == variavel){
                        alert('o valor é igual');
                    }else{
                        alert('o valor é diferente');
                    }
                }
            }
        });
    });
  • 1

    Thanks for the observations were typos and the code was not put into test to verify these conditions. I solved the problem transformed the variable into global type. Anyway thank you for your attention

Browser other questions tagged

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