How to fill data in html input

0

I'm creating a site to study and a question arose, where I created a basic HTML with database and I'm trying to pass some values manually, but when I press the change button, the fields are not filled automatically with the button .

  <script type="text/javascript">
  $("button").click(function() {
    var $id_user = $("input[name='id_user']");
    var $usuario = $("input[name='usuario']");
    var $login = $("input[name='login']");
    var $senha = $("input[name='senha']"); 
    $.ajax({
    url: "alterarconfig.php?id_user=1",
    data: {id_user: 1},
    dataType: "JSON",
    type: "POST",
    success: function retorna(json) {
        $usuario.val(json.usuario);
        $login.val(json.login);
        $senha.val(json.senha);
    }

 });
});  
</script>
<div class="config">
  <div class="row">
    <div class="col-md-6">
      <form method="POST" action="alterarconfig.php?id_user=1">
        <label>ID</label><input readonly="true" type="text" class="form-control" id="id_user" name="id_user" value="<?php $valores['usuario'] ?>"><br>
        <label>Usuário</label><input type="text" class="form-control" id="usuario" name="usuario" value="<?php $valores['usuario'] ?>"><br>
        <label>E-mail/Login</label>
        <input type="text" class="form-control" id="login" name="login" value="<?php $valores['usuario'] ?>"><br>
        <label>Senha Atual</label>
        <input type="password" class="form-control" id="senha" name="senha" value="<?php $valores['usuario'] ?>"><br>
        <label>Endereço</label>
        <input type="text" class="form-control" id="end" name="end"><br>
        <label>Número</label>
        <input type="text" class="form-control" id="numero" name="numero"><br>
        <label>Bairro</label>
        <input type="text" class="form-control" id="bairro" name="bairro"><br>
        <label>Cidade</label>
        <input type="text" class="form-control" id="city" name="city"><br>
        <label>Telefone</label>
        <input type="text" class="form-control" id="tel" name="tel"><br>
        <label>Celular</label>
        <input type="text" class="form-control" id="cel" name="cel"><br>
        <button type="button" class="btn btn-roxo">Alterar</button> 
      </form>
    </div>
  </div>
</div>

<footer id="rodape">
  <div class="container">
    <div class="row">

      <div class="col-md-2">
        <span class="img-logo-footer"></span>
      </div>

      <div class="col-md-10">
        <h4>Contato</h4>
        <ul class="nav">
          <li class="navbar-font"><a href="">Sobre</a></li>
          <li class="navbar-font"><a href="">[email protected]</a></li>
          <li class="navbar-font"><a href="">+55(19)99219-1600</a></li>
        </ul>
      </div>
    </div>
  </div>

My php:

  <?php
session_start() ;

function retorna($id_user){
    try{
        require('conexao.php') ;
        $sql = "SELECT usu.* FROM usuario usu Where usu.id = :id LIMIT 1" ;
        $stmt = $conexao->prepare($sql) ;
        $stmt->execute(array('id' => $id_user));

        $logou = 0 ;

        while($consulta = $stmt->fetch()) {
            $valores['id_user'] = $consulta["id"] ;
            $valores['usuario'] = $consulta["usuario"] ;
            $valores['login'] = $consulta["login"] ;
            $valores['senha'] = $consulta["senha"] ;

            $logou = 1 ;
        }

        if($logou = 0){
            echo "Sem resultado de usuário válido..";
        }
    }
    catch(PDOException $ex){
        echo " ".$ex;
    }
    return json_encode($valores);
}
if(isset($_POST['id_user'])){
    echo retorna($_POST['id_user']);
}
?>

But the page returns blank .. Can anyone help me with this problem?

    
asked by anonymous 25.01.2018 / 01:52

1 answer

1

To fill a form with data that is on another page, you must use jQuery.ajax or XMLHttpRequest (JS Pure) .

You first need to replace the type="submit" attribute with type="button" and remove the action attribute from the Change button.

The type="submit" attribute will redirect you to another page and apparently that's not what you want.

After this change, simply use the code below to request the user data.

$("button").click(function() {
    $.ajax({
        url: "alterarconfig.php?id_user=1",
        data: {id_user: 1},
        dataType: "JSON",
        type: "POST",
        success: function(json) {
            $usuario.val(json.usuario);
            $login.val(json.login);
            $senha.val(json.senha);
        }

    });
});

Another way is to add the code php to your view , or code html . This way you can add the value attribute to the value captured by php . Ex:

<input type="text" value="<?php $valores['usuario'] ?>" />

Here is a complete example of the test I did.

changeconfig.php

<?php
session_start() ;

function retorna($id_user){

    $valores = [];

    try{
        $conexao = new PDO("mysql:dbname=teste;host=localhost:3307", "root", "123456");

        $sql = "SELECT usu.* FROM usuario usu Where usu.id = :id LIMIT 1" ;
        $stmt = $conexao->prepare($sql) ;
        $stmt->execute(array('id' => $id_user));

        while($consulta = $stmt->fetch()) {
            $valores['id_user'] = $consulta["id"] ;
            $valores['usuario'] = $consulta["usuario"] ;
            $valores['login'] = $consulta["login"] ;
            $valores['senha'] = $consulta["senha"] ;
        }

        if (empty($valores)) {
            throw new PDOException("Nenhum valor foi encontrado.");
        }

    } catch(PDOException $ex){
        $valores["error"] = utf8_decode($ex->getMessage());
    }

    return json_encode($valores);
}

if(isset($_POST['id_user'])){
    echo retorna($_POST['id_user']);
}

index.html

<!DOCTYPE hml>
<html>
    <head>
        <title>Title of the document</title>
    </head>

    <body>

        <div class="wait" style="display:none">Aguarde...</div>

        <form method="POST" action="alterarconfig.php?id_user=1">
            <label>ID</label><input readonly="true" type="text" class="form-control" id="id_user" name="id_user" value="1"><br>
            <label>Usuário</label><input type="text" class="form-control" id="usuario" name="usuario" value=""><br>
            <label>E-mail/Login</label>
            <input type="text" class="form-control" id="login" name="login" value=""><br>
            <label>Senha Atual</label>
            <input type="password" class="form-control" id="senha" name="senha" value=""><br>
            <label>Endereço</label>
            <input type="text" class="form-control" id="end" name="end"><br>
            <label>Número</label>
            <input type="text" class="form-control" id="numero" name="numero"><br>
            <label>Bairro</label>
            <input type="text" class="form-control" id="bairro" name="bairro"><br>
            <label>Cidade</label>
            <input type="text" class="form-control" id="city" name="city"><br>
            <label>Telefone</label>
            <input type="text" class="form-control" id="tel" name="tel"><br>
            <label>Celular</label>
            <input type="text" class="form-control" id="cel" name="cel"><br>
            <button type="button" class="btn btn-roxo">Alterar</button> 
        </form>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scripttype="text/javascript">
            $("button").click(function() {
                var id_user = $("input[name='id_user']");
                var usuario = $("input[name='usuario']");
                var login = $("input[name='login']");
                var senha = $("input[name='senha']"); 

                $.ajax({
                    url: "alterarconfig.php?id_user=1",
                    data: {id_user: $(id_user).val()},
                    dataType: "JSON",
                    type: "POST",
                    beforeSend: function() {
                        $(".wait").show();
                    },
                    success: function retorna(json) {
                        if (json.error) {
                            alert(json.error);
                            return;
                        }

                        usuario.val(json.usuario);
                        login.val(json.login);
                        senha.val(json.senha);
                    },
                    complete: function() {
                        $(".wait").hide();
                    }
                });
            });  
        </script>
    </body>
</html>

I added both files to the same folder.

    
25.01.2018 / 02:46