Return database data in <label> with Javascript

Asked

Viewed 799 times

-1

I need to return the database data inside the inputs when selected the "Edit" button without the page being reloaded, however, when clicking on "Edit", I see that the action of the button changes, as the javascript code, but the inputs are not filled in with the data in the database. Follows the script:

$(document).on('click','.update', function(){
    var id = $(this).attr("id");
    $.ajax({
        url:"../control/control_salvaEdicao.php",
        method:"POST",
        data:{id:id},
        datatype:"json",
        success:function(data){
            $('#action').text("Editar");
            $('#id').val(id);
            $('#nome').val(data.nome);
            $('#sobrenome').val(data.sobrenome);
            $('#endereco').val(data.endereco);
        }
    });
});

HTML

<head>
    <title>Cadastro de Pessoas</title>
    <link rel="stylesheet" type="text/css" href="Css/Style.css"/>
    <script language="JavaScript" src="Js/jquery-1.12.3.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">       
</head>
<body>
    <div id="tudo">
        <div id="pessoas">      
        </div>
        <div id="boxcentral" align="center">
            <label>Nome: </label>
            <input type="text" name="nome" id="nome"/>
            </br></br>
            <label>Sobrenome: </label>
            <input type="text" name="sobrenome" id="sobrenome"/>
            </br></br>
            <label>Endereço: </label>
            <input type="text" name="endereco" id="endereco"/>
            </br></br>
            <input type="hidden" name="id" id="id"/>
            <button type="button" name="action" id="action">adicionar</button>
            <div id="resultado">
            </div>  
        </div>

Filing cabinet editeEvento.php

if (isset ($_POST['id'])){

$pessoa = new Pessoa();
$peopleDAO = new PessoaDAO();   

$pessoa->getId($_POST['id']);

        $retornoPessoa = $peopleDAO->buscaPessoaID($pessoa);

        if($retornoPessoa != null){
            foreach ($retornoPessoa as $obj){
                $obj->getId();  
                $obj->getNome();    
                $obj->getSobrenome();   
                $obj->getEndereco();
            }

            return $obj;

        }
}

Filing cabinet salvaEdicao.php

if($_POST["action"]== "editar"){    
$pessoa = new Pessoa();
$pessoaDAO = new PessoaDAO();   

    $pessoa->setId($_POST['id']);
    $pessoa->setNome($_POST['nome']);
    $pessoa->setSobrenome($_POST['sobrenome']);
    $pessoa->setEndereco($_POST['endereco']);



    try{
        $resultado = $pessoaDAO->update($pessoa);
    }catch(exeption $e){
        $erro=$e->getmessage();
        echo $erro;
    }

    if ($resultado == true){
        $sucess_message="Cadastro atualizado com sucesso!";
        echo $sucess_message;
    }       
}       
  • 2

    Could make html available?

  • 1

    How to create a Minimum, Complete and Verifiable example. It would not be the case to print the return on Console? console.log(data); to see if he’s getting back and how he’s coming ?

  • Put the backend and script reset control_salvaEdicao.php

  • I also found it strange that Return is using some "framework"? better change the header to respond as json also (n know if you did elsewhere)

  • and if you remove the foreach and do Return $return]?

  • i would try first of all echo json_encode($returnsPessoa); die(); just to see

  • @wmsouza, I made the change and it was like this https://repl.it/@lucaalmec/Intentagonizingqueenslandheeler, but the problem still persists

  • I only check in HTML if inputs are filled in. How do I print in console?

  • Within success:function(data) in the Javascript put the line console.log(data);, see: What is console.log? and is using the Chrome the shortcut to open is CTRL+SHIT+I

  • with Console.log does not return any information to me on the screen, but I tested with Alert using Alert(data.name)... and all are as undefined except for the ID that is already assigned by the "Edit"

  • Okay, now see that you’re just sending the id as a parameter, you have to send the fields as well, see repl it.

  • The same thing happens, all fields remain undefined except the ID...

Show 7 more comments

1 answer

0

you are only returning a success message, what you have to do is return the updated object:

php:

 if ($resultado == true){
            $sucess_message="Cadastro atualizado com sucesso!";
            echo json_encode([
                   'message' => $sucess_message, 
                   'pessoa' => $pessoa
            ]);
    }    

ajax:

$(document).on('click','.update', function(){
    var id = $(this).attr("id");
    $.ajax({
        url:"../control/control_salvaEdicao.php",
        method:"POST",
        data:{id:id},
        datatype:"json",
        success:function(data){
            $('#action').text("Editar");
            $('#id').val(data.pessoa.id);
            $('#nome').val(data.pessoa.nome);
            $('#sobrenome').val(data.pessoa.sobrenome);
            $('#endereco').val(data.pessoa.endereco);
        }
    });
});

That when you click on the event to save right, if it is in the event to pull the data I believe only the URL of your ajax that is incorrect, should be url:"../control/control_editaEvento.php"

Try putting a console.log on your return from Ajax to see how the result is coming, because if it comes from the editEvento.php file the correct way to get the data is to:

$('#action').text("Editar");
$('#id').val(data.id);
$('#nome').val(data.nome);
$('#sobrenome').val(data.sobrenome);
$('#endereco').val(data.endereco);

The ID is probably coming filled in because note you take the value of the variable you pass to ajax.

Browser other questions tagged

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