Method $_POST returning NULL

Asked

Viewed 906 times

0

Good night. I’m having a problem with my $_POST method, because it only returns me NULL. I have tried from N forms, redesigned design, BD, refiz class by class, etc., but without success.

Where am I wrong? Follow a part of the code:

<?php
    $Item = new Usuario();
    var_dump($Item);
    Esse Retorna >> object(Usuario)#1 (7) { ["id_usuario":"Usuario":private]=> NULL ["nome_usuario":"Usuario":private]=> NULL ["email_usuario":"Usuario":private]=> NULL ["senha_usuario":"Usuario":private]=> NULL ["telfixo_usuario":"Usuario":private]=> NULL ["celular_usuario":"Usuario":private]=> NULL ["nivel_usuario":"Usuario":private]=> NULL }  


    $Item = $Item->Read($_POST['id']);
    var_dump($Item);
    Esse Retorna >> NULL
?>

<section class="row formAdicionarDados">
    <section class="col-md-4">
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon1">Nome *</span>
            <input type="text" class="form-control" id="nome_usuario" placeholder="Nome Completo" required aria-describedby="basic-addon1" value="<?php echo $Item['nome_usuario']; ?>">
        </div>
    </section>

    <section class="col-md-4">
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon1">e-mail *</span>
            <input type="text" class="form-control" id="email_usuario" placeholder="[email protected]" required aria-describedby="basic-addon1" value="<?php echo $Item['email_usuario']; ?>">
        </div>
    </section>

    <section class="col-md-4">
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon1">Senha *</span>
            <input type="password" class="form-control" id="senha_usuario" placeholder="Senha" required aria-describedby="basic-addon1" value="<?php echo $Item['senha_usuario']; ?>">
        </div>
    </section>    
</section>

<br>

<section class="row formAdicionarDados">
    <section class="col-md-4">
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon1">Telefone Fixo *</span>
            <input type="text" class="form-control" id="telfixo_usuario" placeholder="Tel. Fixo" required aria-describedby="basic-addon1" value="<?php echo $Item['telfixo_usuario']; ?>">
        </div>
    </section>

    <section class="col-md-4">
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon1">Celular *</span>
            <input type="text" class="form-control" id="celular_usuario" placeholder="Celular" required aria-describedby="basic-addon1" value="<?php echo $Item['celular_usuario']; ?>">
        </div>
    </section>

    <section class="col-md-4">
        <div class="input-group">
            <span class="input-group-addon" id="basic-addon1">Nível de Acesso *</span>
            <select class="form-control" id="nivel_usuario" required>
            <option value=""> Escolha uma opção </option>
            <option value="1"> 1 </option>
            <option value="2"> 2 </option>
            <option value="3"> 3 </option>
        </div>
    </section>
</section>

<input type="hidden" id="id_usuario" value="<?php echo $Item['id_usuario'];?>">

Javascript:

$('#Salvar').click(function(e){
            e.preventDefault();

            //1 instaciar e recuperar valores dos inputs
            var id_usuario = $('#id_usuario').val();
            var nome_usuario = $('#nome_usuario').val();
            var email_usuario = $('#email_usuario').val();
            var senha_usuario = $('#senha_usuario').val();
            var telfixo_usuario = $('#telfixo_usuario').val();
            var celular_usuario = $('#celular_usuario').val();
            var nivel_usuario = $('#nivel_usuario').val();

            //2 validar os inputs
            if(nome_usuario === "" || email_usuario === "" || senha_usuario === "" || telfixo_usuario === "" || celular_usuario === "" || nivel_usuario === ""){
                return alert('Todos os campos com (*) devem ser preenchidos!');
            } else {
                //emailtester entra aqui
                var emailtester = false;
                var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
                emailtester = re.test(email_usuario);
                if(!emailtester){

                    return alert("Formato de email incorreto. Corrija o campo e tente novamente");
                }
                else{
                    $.ajax({
                       url: 'engine/controllers/usuario.php',
                       data: {
                            id_usuario : id_usuario,
                            nome_usuario : nome_usuario,
                            email_usuario : email_usuario,
                            senha_usuario : senha_usuario,
                            telfixo_usuario : telfixo_usuario,
                            celular_usuario : celular_usuario,
                            nivel_usuario : nivel_usuario,

                            action: 'update'
                       },
                       error: function() {
                            alert('Erro na conexão com o servidor. Tente novamente em alguns segundos.');
                       },
                       success: function(data) {
                            console.log(data);
                            if(data === 'true'){
                                alert('Item editado com sucesso!');
                                $('#loader').load('viewers/cadastro/usuario.lista.php');
                            } else {
                                alert('Erro ao conectar com banco de dados. Aguarde e tente novamente em alguns instantes.');   
                            }
                       },

                       type: 'POST'
                    }); 
                }                   
            }
        });

        $('#Excluir').click(function(e) {
            e.preventDefault();     
            var id = $('#id_usuario').val();
            alert(id);
            if(confirm("Tem certeza que deseja excluir este dado?")){
                $.ajax({
                   url: 'engine/controllers/usuario.php',
                   data: {
                        id_usuario : id,
                        nome_usuario : null,
                        email_usuario : null,
                        senha_usuario : null,
                        telfixo_usuario : null,
                        celular_usuario : null,
                        nivel_usuario : null,

                        action: 'delete'
                   },
                   error: function() {
                        alert('Erro na conexão com o servidor. Tente novamente em alguns segundos.');
                   },
                   success: function(data) {
                        if(data === 'true'){
                            alert('Item deletado com sucesso!');
                            $('#loader').load('viewers/cadastro/usuario.lista.php');
                        } else {
                            alert('Erro ao conectar com banco de dados. Aguarde e tente novamente em alguns instantes.');
                        }
                   },

                   type: 'POST'
                }); 
            }   
        });

Class with Read($id function):

class Usuario{  
        private $id_usuario;
        private $nome_usuario;
        private $email_usuario;
        private $senha_usuario;
        private $telfixo_usuario;
        private $celular_usuario;
        private $nivel_usuario;

        public function SetValues($id_usuario, $nome_usuario, $email_usuario, $senha_usuario, $telfixo_usuario, $celular_usuario, $nivel_usuario){          
            $this->id_usuario = $id_usuario;
            $this->nome_usuario = $nome_usuario;
            $this->email_usuario = $email_usuario;
            $this->senha_usuario = $senha_usuario;
            $this->telfixo_usuario = $telfixo_usuario;
            $this->celular_usuario = $celular_usuario;
            $this->nivel_usuario = $nivel_usuario;

        }

public function Create(){...}

public function Read($id){
            $sql = "
                SELECT
                     t2.id_usuario,
                     t2.nome_usuario,
                     t2.email_usuario,
                     t2.senha_usuario,
                     t2.telfixo_usuario,
                     t2.celular_usuario,
                     t2.nivel_usuario
                FROM
                    usuario AS t2
                WHERE
                    t2.id_usuario = '$id'
            ";

            $DB = new DB();
            $DB->open();
            $Data = $DB->fetchData($sql);

            $DB->close();
            return $Data[0]; 
        }

Controller:

<?php
    require_once "../config.php";

    $id_usuario= $_POST['id_usuario'];
    $nome_usuario= $_POST['nome_usuario'];
    $email_usuario= $_POST['email_usuario'];
    $senha_usuario= $_POST['senha_usuario'];
    $telfixo_usuario= $_POST['telfixo_usuario'];
    $celular_usuario= $_POST['celular_usuario'];
    $nivel_usuario= $_POST['nivel_usuario'];

    $action = $_POST['action'];

    $Item = new Usuario();
    $Item->SetValues($id_usuario, $nome_usuario, $email_usuario, $senha_usuario, $telfixo_usuario, $celular_usuario, $nivel_usuario);

    switch($action){
        case 'create':
            $res = $Item->Create();
            if($res === NULL){
                $res = "true";
            }else{
                $res = "false"; 
            }           

            echo $res;
        break;  

        case 'update':
            $res = $Item->Update();

            if($res === NULL){
                $res= 'true';   
            }else{
                $res = 'false'; 
            }
            echo $res;
        break;  

        case 'delete':
            $res = $Item->Delete();
            if($res === NULL){
                $res= 'true';   
            }else{
                $res = 'false'; 
            }
            echo $res;
        break;
    }
?>
  • Give a var_dump($_POST) before the require_once "../config.php"; and sees the result, if it really comes set the $_POST['id']. Put the form in the question too, it might be some mistake in it.

  • This was the return after the var_dump before the require_once: array(0) { } Notice: Undefined index: id_usuario in C: xampp htdocs engine controllers usuario.php on line 6 Notice: Undefined index: nome_usuario in C: xampp htdocs engine controllers usuario.php on line 7 ...

  • How is the form being posted? Javascript?

  • 1

    Sorry for the ignorance... but does your HTML form have action? At least in the excerpt of the code you posted I did not see the opening of the "form" tag with the action. This could be why the variables are not going by post.

  • @Allanandrade, yes. It’s being done by JS.

  • @Rodrigotognin, I’m doing an action: 'update' by JS from the id of a Save button and an action: 'delete' from the id of a Delete button.

  • Most likely the error is in this js. Puts it too

  • Added, @Andrévicente

  • Which jquery version is using?

Show 4 more comments

1 answer

2

Guys, I found the mistake. Blessed be the case sensitive.

There were two errors:

The first was in mine "foreach($Item as $itemRow)" where at the time of passing the id_usuario value I was using "itemrow" or instead of "itemRow".

The second error was actually in Javascript, where I was assigning the id value to the function but was not passing it in the execution.

Before:

$('.EditarItem').click(function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    alert(id);
    $('#loader').load('viewers/cadastro/usuario.editar.php');
});

Afterward:

$('.EditarItem').click(function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    alert(id);
    $('#loader').load('viewers/cadastro/usuario.editar.php', {id:id});
});

Thank you very much!

Browser other questions tagged

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