AJAX return handling with JQUERY

1

I have the following script, which processes the form and updates the list # div by ajax:

<script type="text/javascript">
    $(document).ready(function(){
        $("#formulario").on("submit", function(e){
            e.preventDefault();
            var cdb = $("#cdb").val();
            $.ajax({
                url: "confere.php",
                method: "POST",
                dataType: "html",
                data: {cdb: cdb}
            }).done(function(data){
                $("#cdb").val("");
                $("#cdb").focus();
                listar();
            }).fail(function(data){
                alert("Erro");
            });
        });
    });
    function listar() {
        $.ajax({
            url:"lista.php",
            success: function (textStatus) {      
                $('#lista').html(textStatus);
            }
        }); 
    }
</script>

What I would like was to treat the return of confere.php , and not only validate with .done and .fail .

For example: The return of confere.php can be "X", "Y", "Z", and according to return, perform an action.

File: confere.php

<?php

$cdb = filter_input(INPUT_POST,'cdb');
$valor = $cdb/10;

gravar($valor);

function gravar($texto){
    $arquivo = "temp.txt";
    $fp = fopen($arquivo, "a+");
    fwrite($fp, $texto . ";");
    fclose($fp);
}

?>
    
asked by anonymous 22.01.2018 / 13:39

3 answers

2

You can return the page PHP to JSON :

When it works, you return true:

echo json_encode(array(
  "result" => true
));

When not, you return false:

echo json_encode(array(
  "result" => false
));

You can also return other values together, for example, when the error returns the error message:

echo json_encode(array(
  "result" => false,
  "message" => "Erro x"
));

To address this response it does the following:

$(document).ready(function(){
    $("#formulario").on("submit", function(e){
        e.preventDefault();
        var cdb = $("#cdb").val();
        $.ajax({
            url: "confere.php",
            method: "POST",
            dataType: "json",
            data: {cdb: cdb}
        }).done(function(data){
            if (data.result){
                $("#cdb").val("");
                $("#cdb").focus();
               listar();
            } else{
                alert(data.message);
            }
        }).fail(function(data){
            alert("Erro");
        });
    });
});
    
22.01.2018 / 13:50
2

As you did not put an example of your return I will assume does not do it that way. One of the ways to do this is by returning a JSON in the following format:

{
    "retorno": "x",
    "dados":"seus dados vão aqui",
    "erro":true,
    "msg-erro":"usuário não autorizado a fazer operação"
}

In this example I have 4 data returning from my script. A retorno that tells me what kind of operation I'm going to do on my front, dados that can contain all the returned data (it can even have one JSON inside another), erro that informs me if I hear any error in application and msg-erro that contains the error message, if any.

In this template you could do the following to test your return.

.done(function(data){
    if(data.retorno == "x"){
        alert('retorno do tipo X');
    }else if(data.retorno == "Y"){
        alert('retorno do tipo Y');
    }
}

This was just an example of the return type, but you can build your own structure. I like this template because I already tested the error variable face, and if it forms true I already display the error message pro user and I stop my script.

    
22.01.2018 / 13:54
2

Friend, can you post the feedback from your "confere.php"?

Because ajax expects the return to be in JSON format, and if the return is a valid JSON, it already parses an object automatically.

For example, I usually use in my applications a return containing two (or three) properties: 1 - success: true or false (to validate processing) 2 - date: json object 3 - message: if success is false, the message field returns a custom message about the failure error

Exemplifying the return in code would look something like this:

{
  success: true,
  data: {
    nome: "Marcelo",
    sobrenome: "Tadeu"
  }
}

ou 

{
  success: false,
  message: "Usuario ou senha inválido(s)"
}

and in the application (ajax return) it would do something like this:

$.ajax({
    url: "confere.php",
    method: "POST",
    data: {cdb: cdb}
}).done(function(data){
    var retorno = data;
    
    if(retorno.success){
      $('#nome').html(retorno.data.nome);
      $('#sobrenome').html(retorno.data.sobrenome);
    }else{
      alert(retorno.message);
    };
}).fail(function(err){
    alert("Erro no request: "+err);
});

If by chance your return header does not come as "application / json", you need to turn the text into json object:

var resposta = $.parseJSON(data);
    
22.01.2018 / 13:56