Load Value in Input

0

Good morning,

I'm trying to load a value into the Input after the user clicks the button.

// Este é o Botão
    <button type="button" class="btn btn-default" tabindex="-1" onclick="id_host()"> Identificar Nome </button>

When he clicks this button, I want him to go to a page .php and make a gethostname() and return with the result, assigning in the input.

Follow the code for better understanding:

// Função quando Clicar no Botão.
    function id_host() {                    
    var n_pc = $("#conteudo").load("processa.php");
    document.getElementById('#conteudo').value = n_pc;
    }

This is the Input I want popular with the result of processa.php

<input type="text" class="form-control" name="conteudo" id="conteudo" value="">

Can anyone help me?

Thank you.

    
asked by anonymous 25.09.2014 / 15:45

2 answers

2
The load function is to load a content (usually some HTML) within a given element, ie in your case $("#conteudo").load("processa.php"); you are loading the content of processa.php into the element $("#conteudo") .

Use the ajax function instead of load , and also have the result placed in the callback function. I also recommend performing the return with json format.

Example

$.ajax({
   url: 'processa.php',
   dataType: 'json',
   success: function(data){
      $('#conteudo').val(data.texto);
   },
   error: function(jqXHR, textStatus, errorThrown) {
      console.log(jqXHR);
      console.log(textStatus, errorThrown);
   }
});

process.php

<?php
   echo json_encode(Array('texto' => 'texto de exemplo'));

Explaining

The part

   success: function(data){
      $('#conteudo').val(data.texto);
   }

will be executed when ajax receives the return of processa.php , and this return will come in the data parameter. The texto property of the data parameter was set there in processa.php , encoding the json format by the json_encode function.

If the processa.php script has an error, and does not execute correctly, then the success: function(data){ ... } function will not be executed, instead the error: function(jqXHR, textStatus, errorThrown) { ... } function will be executed, and the parameters will be objects containing the error information , in it you can put a alert informing the user that the query can not be completed, thus:

   error: function(jqXHR, textStatus, errorThrown) {
      console.log(jqXHR);
      console.log(textStatus, errorThrown);
      alert('Não foi possível completar a requisição.');
   }
    
25.09.2014 / 19:04
0

Hello, try using the .val() method

// Função quando Clicar no Botão.
    function id_host() {                    
    var n_pc = $("#conteudo").load("processa.php");

     //Use o método VAL do jquery
    $("#conteudo").val(n_pc);
    }

If it does not work, try adding a return to the button.

// Este é o Botão
    <button type="button" class="btn btn-default" tabindex="-1" onclick="return id_host();"> Identificar Nome </button>
    
25.09.2014 / 18:39