AJAX Return Handling with JQUERY

Asked

Viewed 2,980 times

0

I have the following script, which processes the form and updates the div #list 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 to treat is the return of confere.php, and not only validate with the .done and .fail.

For example: The return of confere.php may be "X", "Y", "Z", and upon return, perform an action.

Filing cabinet: 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);
}

?>
  • 1

    You know what the parameter is data that you used on .done?

  • No puts, and I hadn’t noticed. I know almost nothing about JQUERY. If you have any good articles about these requests, I really appreciate it !

3 answers

3


You can make the page return PHP in JSON:

When it works out, you come back 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 error returns the error message:

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

To treat this response do as follows:

$(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");
        });
    });
});
  • 2

    If you use the dataType: 'json' you don’t need the JSON.parse

  • The "default" return is in JSON then ? If I change to dataType: 'json' will keep working what I’m going through POST?

  • Yes, I’ll continue, I’ll change the answer

  • Changed, thanks for the remark @Andersoncarloswoss

  • 1

    If I put dataType: "json" already gives me failure in the request. If I let dataType: "html" and the return alert(data.message) appears undefined.

  • What to your page PHP is returning?

  • Oops ! I just found the reason. It was coming a "0". I put dataType: "json" and now it was ! Thank you very much !

Show 2 more comments

2

As you did not put an example of your return I will assume it does not do so. One of the ways to do this is to return 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 which may contain all returned data (including a JSON inside another), erro informs me if there is any error in the application and msg-erro containing the error message, if any.

In this model 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 kind of feedback, but you can build your own structure. I like this model because I already test the face error variable, and if it form true I already display the error message to the user and I stop my script.

1

Friend, you can post the return of your "confer.php"?

Because ajax expects the return to be in JSON format, and if the return is a valid JSON it already parses to 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 fault error

Exemplifying the return in code, it would be 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) 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 some chance your return header does not come as "application/json", you need to turn the text into json object:

var resposta = $.parseJSON(data);

  • The confere.php no return. It only takes the content of cdb by POST and saves in a txt.

  • I understood, so in this you do: if(data == 'X'){ does this }Else if(data == 'Y'){ does that }Else if(data == 'Z'){ does something else } E if error 500 the AJAX will already route to your . fail()... Hence the need to return something for you to have greater control...

  • In your check.php, after fclose($Fp), from an echo 'X' to be able to handle it in ajax...

Browser other questions tagged

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