Manipulate JSON with jQuery

Asked

Viewed 79 times

0

I have a jQuery with $.ajax who 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 don’t understand is how to manipulate this data config.php returns, printing the wrong answers in div id="erro" according to the status.

  • 1

    You should be wearing dataType: 'json' instead of dataType: 'html'

  • is that this ajax makes the request sending data to a php that will generate the json with the data sent, if I change something in sending this data ?

  • 1

    No, the dataType only refers to the expected return.

1 answer

0


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

The return variable resultado will be the JSON, so just take 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;

    })
}

Browser other questions tagged

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