How to insert returned value into form fields with jQuery?

Asked

Viewed 726 times

7

Accurate, after consulting in BD insert returned values into fields of a form, as I will use these fields to make a change to the BD, the call to search is working correctly and is configured this way, call the function BuscaDados passing the parameters Operacao and IdFase to the page pProcessoFase.php that returns the searched values but in return I am not able to assign the values in the form fields, I gave a console.log in return and see this see:

[{"Descricao":"controle","Data":"2015-09-03","Hora":"17:36:00","IdTipoFase":1}]
function BuscaDados(IdFase) {
    var params = {
        Operacao: 'BuscaUnica',
        IdFase: IdFase
    };      
    $.post(
        'pProcessoFase.php',
        params,
        function( json, textStatus, jQxhr ){
            if (jQxhr.responseText != "[]") {
                try {
                    if (jQxhr.readyState === 4) {
                        if (jQxhr.status === 200) {
                            var registro = JSON.parse(jQxhr.responseText);

                            console.log("RESPOSTA DA CONSULTA: " + jQxhr.responseText);

                            //Atribui valores aos campos
                            $('#sDescricao').val(registro[0].Descricao);
                            $('#dData').val(registro[0].Data);  
                            $('#dHora').val(registro[0].Hora);  
                            $('#IdTipoFas').val(registro[0].IdTipoFas);                         
                        } else {
                            var dialogInstance = BootstrapDialog.show({
                                title: 'ERRO',
                                type: BootstrapDialog.TYPE_DANGER,
                                message: 'Ocorreu um erro na requisição dos dados. Tente novamente.'
                            }); 
                        }
                    }
                }
                catch( e ) {
                    console.log(e);
                    var dialogInstance = BootstrapDialog.show({
                        title: 'ERRO',
                        type: BootstrapDialog.TYPE_DANGER,
                        message: 'Ocorreu um erro na requisição dos dados. Tente novamente.'
                    }); 
                }
            }
        },
        'json'
    )
    .fail(function( jqXhr, textStatus, errorThrown ){
        try {
            var json = $.parseJSON(jqXHR.responseText);
            var dialogInstance = BootstrapDialog.show({
                title: 'ERRO',
                type: BootstrapDialog.TYPE_DANGER,
                message: json.msg
            }); 
        } catch(e) { 
            var dialogInstance = BootstrapDialog.show({
                title: 'ERRO',
                type: BootstrapDialog.TYPE_DANGER,
                message: json.msg
            }); 
        }
    });
}

Search on the page pProcessoFase.php:

if ($_POST["Operacao"] == 'BuscaUnica') {

    $sql = "SELECT Descricao, Data, Hora, IdTipoFase FROM gerFaseContrato WHERE IdFase = '". $_POST['IdFase']."' ";

    $stmt = $conn->prepare($sql);
    if($stmt->execute()){
        $data = array();    
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        header('Content-Type: application/json');
        echo json_encode($data);
        $stmt->close();
    }else{
        $aretorno["msg"] = "Ocorreu um erro na inclusão dos dados: " . $stmt->error . ". Verifique.";
        $aretorno["status"] = "ERRO";
        header('Content-Type: application/json');
        echo json_encode($aretorno);
    }

    $conn->close();
    exit;
}

The form where I am trying to enter the information:

<body>
<form class="form-horizontal" id="frmDadosFase">
  <fieldset>
    <div class="form-group">
      <label class="col-md-4 control-label" for="sDescricao">Descrição</label>
      <div class="col-md-4">
        <textarea class="form-control" id="sDescricao" name="sDescricao"></textarea>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label" for="dData">Data</label>
      <div class="col-md-4" id="sandbox-container">
        <div class="input-group date">
          <input name="dData" type="text" class="form-control" id="dData">
          <span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span> </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label" for="dHora">Hora</label>
      <div class="col-md-4">
        <input id="dHora" name="dHora" placeholder="" class="form-control input-md" type="time">
      </div>
    </div>
    <div class="form-group">
      <label class="col-md-4 control-label" for="IdTipoFase">Tipo Fase</label>
      <div class="col-md-4">
        <textarea class="form-control" id="IdTipoFase" name="IdTipoFase"></textarea>
      </div>
    </div>
  </fieldset>
</form>
</body>

  • What is the error that gives? what is lacking? what gives console.log(registro[0].Descricao);?

  • Hello @Sergio, you are not accusing me of any mistakes and all the fields I need are returned.

  • So what’s not working? The.log console I mentioned above works fine?

  • Yes, the console.log brings the searched data and I’m not getting to play it in the form fields.

  • What is the HTML of #sDescricao for example? you can put the rest too?

1 answer

6


I followed a working example:

var jsonString = '[{"Descricao":"controle","Data":"2015-09-03","Hora":"17:36:00","IdTipoFase":1}]';

var registro = JSON.parse(jsonString);

$(document).ready(function() {
  $('#sDescricao').val(registro[0].Descricao);
  $('#dData').val(registro[0].Data);
  $('#dHora').val(registro[0].Hora);
  $('#IdTipoFase').val(registro[0].IdTipoFase);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <form class="form-horizontal" id="frmDadosFase">
    <fieldset>
      <div class="form-group">
        <label class="col-md-4 control-label" for="sDescricao">Descrição</label>
        <div class="col-md-4">
          <textarea class="form-control" id="sDescricao" name="sDescricao"></textarea>
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4 control-label" for="dData">Data</label>
        <div class="col-md-4" id="sandbox-container">
          <div class="input-group date">
            <input name="dData" type="text" class="form-control" id="dData"> <span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span> 
          </div>
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4 control-label" for="dHora">Hora</label>
        <div class="col-md-4">
          <input id="dHora" name="dHora" placeholder="" class="form-control input-md" type="time">
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4 control-label" for="IdTipoFase">Tipo Fase</label>
        <div class="col-md-4">
          <textarea class="form-control" id="IdTipoFase" name="IdTipoFase"></textarea>
        </div>
      </div>
    </fieldset>
  </form>
</body>

  • 1

    Hello @henriquedpereira, thanks for the example and the work of putting together the whole scheme.

Browser other questions tagged

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