How to fill data in html input

Asked

Viewed 1,899 times

0

I am creating a site for study and a question arose, where I created a Basic HTML with database and I am 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']);
}
?>

However, the page returns blank.. someone can help me with this problem?

  • Do you want to return what data? It’s not working because the url alterarconfig.php needs a parameter. Ex: alterarconfig.php?id_user=1. When you assign method="POST" it is necessary to use $_POST['id_user'] to capture that value. Oh, and there’s an error in funcion, the correct is function

  • I made the edits and brought the results, but I still haven’t been able to fill in the input with the json result. I would like to know if there is another way to make these changes ?

  • You don’t need this ?id_user=1 because it is already sent by Ajax in {id_user: 1}

  • Put in the first line of Success: console.log(json) and let us know what appears.

1 answer

1


To fill out a form with data that is on another page, it is necessary to use jQuery.ajax or XMLHttpRequest (JS Puro).

First you need to replace the attribute type="submit" for type="button" and remove the attribute action button Alter.

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

After this change just 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 in his view, or code html. This way you can add the attribute value with the value captured by php. Ex:

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

Here is a complete example of the test I did.

alterarconfig.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>

        <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: $(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 in the same folder.

  • Thanks for the help, he did not redirect page as reported, but still did not bring any value in the previously said fields. I changed the question to see how I changed the code.

  • @Gabrielhenrique added a more complete example. I didn’t use database connection because it was just a simple test. You have checked if the page is actually returning the data?

  • is not actually updating the page, but the page alterrconfig.php returns the values normally, but the input does not receive the data.

  • @Gabrielhenrique I added a complete code. Before clicking the "Change" button press F12 and note the request in the "Network" tab. The code is very simple and these parts I will leave for you to refactor later. Ps.: Don’t forget to adapt the connection data to the database.

  • Friend, your html worked perfectly, without me changing anything in alterarconfig.php. I will redo the page and see what was causing update conflict and data presentation.

  • I found out!! There were other scripts that invalidated the button execution, it worked perfectly! Thank you all!

Show 1 more comment

Browser other questions tagged

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