Working with the result of the return of an ajax request with jquery

2

I would like to know if it is possible to compare a returned value of 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 inside the Ajax function.

How can I do this check as 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');
                    }
                }
            }
        });
    }

    
asked by anonymous 14.11.2017 / 09:24

1 answer

0

Function on the first line is spelled wrong. Forgot the last parentheses and semicolon to close .ready() .

Furthermore, it is likely that your num is not receiving result , since I noticed that you are trying to receive an object but you are passing it as if it were an array. The best way to check this is by putting a console.log(result) right after 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');
                    }
                }
            }
        });
    });
    
14.11.2017 / 11:18