Handle JSON with jQuery

0

I have a jQuery with $.ajax that sends a request to my config.php which in turn returns a json_array :

function enviar(){
    var bin = $("#bin_id").val();
    var linhaenviar = bin.split("\n");
    var index = 0;
    linhaenviar.forEach(function(value){

        setTimeout(
        function(){
            $.ajax({
                url: 'config.php',
                type: 'POST',
                dataType: 'html',
                data: "bin=" + value,
                success: function(resultado){
            }
        })

    }, 10 * index);

    index = index + 1;

    })
}

The returned array is this:

"{\"pergunta\":\"qual a cor do céu\",\"resposta\":\"azul\",\"status\":\"acertou\"}"

What I do not understand is how to handle this data that config.php returns by printing the wrong answers in div id="erro" according to status.

    
asked by anonymous 22.10.2017 / 13:45

1 answer

0

First of all, as mentioned in the comments, change dataType: 'html' to dataType: 'json' (the return will be a JSON object).

The return variable resultado will be JSON, so just get the value status with resultado.status and make the comparison if the answer is correct:

function enviar(){
    var bin = $("#bin_id").val();
    var linhaenviar = bin.split("\n");
    var index = 0;
    linhaenviar.forEach(function(value){

        setTimeout(
        function(){
            $.ajax({
                url: 'config.php',
                type: 'POST',
                dataType: 'html',
                data: "bin=" + value,
                success: function(resultado){
                    if(resultado.status != "acertou"){
                        $("#erro").append("Resposta errada<br>");
                    }
            }
        })

    }, 10 * index);

    index = index + 1;

    })
}
    
22.10.2017 / 16:40