How to show the error message of validating a data on the screen with append?

Asked

Viewed 45 times

-2

I am trying to sketch as in the image below the mistakes committed by erroneous data entry in the form. However, it only works when data is entered correctly.

A mensagem quando se insere corretamente os dados é "Dados inseridos corretamente"

The javascript code is

$("#formCadastro").on("submit", function (event) {
event.preventDefault();
var dados = $(this).serialize();

$.ajax({
    url: getRoot() + 'controllers/controllerCadastro',
    type: "POST",
    dataType: "json",
    data: dados,
    success: function (xhr) {
        $(".retornoCad").empty();
        $(".retornoCad").append("Dados inseridos com sucesso!");
    },
    error: function (xhr) {
        $(".retornoCad").empty();
        getCaptcha();
        $.each(xhr.response, function(key,value){
            $(".retornoCad").append(value + '<br>');
        });
        
    }
});

});

And the validation . php is

public function validateFinalCad($arrVar)
    {
        if (count($this->getErro()) > 0) {
        
            $arrResponse = [
                // print_r($this->getErro())
                "retorno" => "erro",
                "erros" => print_r($this->getErro())
            ];
        } else {
           $arrResponse = [
                // print_r($this->getErro())
                "retorno" => "success",
                "erros" => null
            ];
            /*$this->cadastro->insertCad($arrVar);*/
        }
        return json_encode($arrResponse);
    }
  • If the validation response returns an HTTP response status 4**, 5** (example 422,500) then you can validate it by error : . See developer tools > network > XHR for response and code. Also check Success and error using console.log(xhr) to debug messages etc.

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativations worth understanding What is the Stack Overflow and read the Stack Overflow Survival Guide (summarized) in Portuguese.

  • I will re-edit. But the problem is simple, so I didn’t write as much.

2 answers

1

Hello,

Disregarding other possible flaws, I believe the problem lies in the function print_r.

According to the documentation, it prints the contents of the variable in a "human readable" manner. But in your case, you want her to return your content. Therefore, you must pass the second parameter to indicate this, through a value that is evaluated as TRUE.

https://www.php.net/manual/en/function.print-r.php

public function validateFinalCad($arrVar)
    {
        if (count($this->getErro()) > 0) {
        
            $arrResponse = [
                // print_r($this->getErro())
                "retorno" => "erro",
                // "erros" => print_r($this->getErro()) o erro está aqui
                "erros" => print_r($this->getErro(), true) // irá retornar o conteúdo de '$this->getErro()' e não escrevêlos (que é o que ela faz por default)
            ];
        } else {
           $arrResponse = [
                // print_r($this->getErro())
                "retorno" => "success",
                "erros" => null
            ];
            /*$this->cadastro->insertCad($arrVar);*/
        }
        return json_encode($arrResponse);
    }


  [1]: https://www.php.net/manual/en/function.print-r.php
  • I used the above amendment. However, when placing "true", it displays the message "Data entered correctly", not the error referring to not validating the data entered incorrectly.

  • In this case, you should check the getErro() method, because it is returning this text. The added trua causes the message that would be sent to the HTML stream to be returned by the function. At no time is the content changed.

1

I will leave a small source for study and better understanding of the ajax request using jquery. For this post I used this fake api for testing https://jsonplaceholder.typicode.com/

View logs in the browser console.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">

    // ID = 1 EXISTENTE
    $.ajax({
        url: 'http://jsonplaceholder.typicode.com/todos/1',
        type: "GET",
        dataType: "json",
        success: function (xhr) {
            //OBVIAMENTE
            console.log('SUCESSO: ', xhr);
        }
    });


    // ID = -1 INEXISTENTE (error)
    $.ajax({
        url: 'http://jsonplaceholder.typicode.com/todos/-1',
        type: "GET",
        dataType: "json",
        success: function (xhr) {
            console.log('SUCESSO: ', xhr);
        },
        error: function (xhr) {
            //status > 400 aqui
            console.log('ERRO: ', xhr);
            console.log('STATUS CODE: ', xhr.status);
            console.log('STATUS TEXT: ', xhr.statusText);
            console.log('RESPONSE JSON: ', xhr.responseJSON);
            console.log('RESPONSE JSON: ', xhr.responseText);
        }
    });

    // ID = -1  INEXISTENTE (utilizando fail)
    $.ajax({
        url: 'http://jsonplaceholder.typicode.com/todos/-1',
        type: "GET",
        dataType: "json",
        success: function (xhr) {
            console.log('SUCESSO: ', xhr);
        }
    }).fail(function(xhr) {
        //status > 400 aqui
        console.log('ERRO USANDO FAIL');
        console.log('ERRO: ', xhr);
        console.log('STATUS CODE: ', xhr.status);
        console.log('STATUS TEXT: ', xhr.statusText);
        console.log('RESPONSE JSON: ', xhr.responseJSON);
        console.log('RESPONSE JSON: ', xhr.responseText);
    });
</script>

Complement the post with the reading of this post What to use in Ajax, Success or done?

  • 1

    When negative comment the reason why I can improve in the next posts. :)

Browser other questions tagged

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