Set value for combo with Ajax

Asked

Viewed 505 times

1

I use the script below to feed some text fields with Oracle database values. But a situation has arisen in which I need to feed a combination of two values (ACTIVE and INACTIVE). In Ajax below, it returns the values of the database but not arrow in index.php. If I take the 'situation' field it feeds the other 2 (name and code). But if I leave it active, it stops in the 'Searching...". How do I set the values of the bank in the combobox? Thanks

INDEX.php

              <tr>
                 <td>Código (4 digitos): </td>
                 <td><input type = "text" name="codigo" id="codigo" size = 15 maxlength = 4 onkeyup="troca_campo2(this)" onkeypress="return SomenteNumero(event)"></td>
              </tr>


              <tr>
                 <td>Nome Completo: </td>
                 <td><input type="text" id="nome" name="nome" size=70 maxlength=50 onkeyup="this.value = this.value.toUpperCase()"></td>
               </tr>

              <tr>
                  <td>Situação:</td>
                  <td><select name="situacao">
                       <option id="situacaoA" value="ATIVO">ATIVO</option>
                       <option id="situacaoI" value="INATIVO">INATIVO</option>
                       </select></td>
              </tr>

ajax.JS

/**
  * Função para criar um objeto XMLHTTPRequest
  */
 function CriaRequest() {
     try{
         request = new XMLHttpRequest();
     }catch (IEAtual){

         try{
             request = new ActiveXObject("Msxml2.XMLHTTP");
         }catch(IEAntigo){

             try{
                 request = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(falha){
                 request = false;
             }
         }
     }

     if (!request)
         alert("Seu Navegador não suporta Ajax!");
     else
         return request;
}

//Não executa nada até a execução terminar
var requestActive = false;

function getDados() {
    if (requestActive) return;
    requestActive = true;
    // Declaração de Variáveis
    /* Caso for necessário passar mais parametros além do nome
     * basta adicionar uma variável aqui e editar no GET
     */
    var ids = ["codigo", "nome", "situacao"];
    var cracha = document.getElementById("cracha").value; //CAMPO QUE VEM DO INDEX.PHP
    var result = document.getElementById("content"); //DIV DE RETORNO DOS DADOS
    var xmlreq = CriaRequest();

    // Exibe a mensagem de progresso
    //result.innerHTML = '<img src="images/Progresso.gif"/>';
    ids.forEach(function (id) {
        document.getElementById(id).value = 'Pesquisando...';
    });

    // Iniciar uma requisição
    // Se for colocar mais variáveis, é aqui. Exemplo: processa.php?txtnome=" + nome + '&admissao=' + admissao
    xmlreq.open("GET", "processa.php?cracha=" + cracha, true);

    // Atribui uma função para ser executada sempre que houver uma mudança de estado
    xmlreq.onreadystatechange = function () {
        // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4)
        if (xmlreq.readyState == 4) {
            // Verifica se o arquivo foi encontrado com sucesso
            if (xmlreq.status == 200) {
                //Se o retorno foi vazio do Oracle
                if (xmlreq.responseText == "") {
                    document.getElementById("cracha").focus();
                    document.getElementById("cracha").value = '';
                    ids.forEach(function (id) {
                        document.getElementById(id).value = 'NÃO ENCONTRADO!';
                    });
                //Se encontrou dados
                } else {
                    //Aqui recebe os dados do processa.php, abre e aplica nos campos desejados
                    var dados = JSON.parse(xmlreq.responseText);
                    // função para preencher os campos com os dados
                    ids.forEach(function (id) {
                        document.getElementById(id).value = dados[id];
                    });
                }
            } else {
                result.innerHTML = "Erro: " + xmlreq.statusText;
            }
        }
        requestActive = false;
    };
    xmlreq.send(null);
}

  • You can give an example of what is returned from the server to ajax?

2 answers

1

There’s probably an error in your console, as I suspect that the moment you try to access document.getElementById(id) where the id is equal to situacao, is not found because your combo has no id, only name. Then he tries to assign value to the property value of null.

Anyway, you should do a different treatment for the combo inside the loop:

ids.forEach(function (id) {
    var el = document.getElementById(id);

    if (el != null) {
        if (el.type && el.type == "text") {
            el.value = 'NÃO ENCONTRADO!';
        }
        else if (el.tagName == "select") {
            el.disabled = true;
        }
    }
});

Or something like that, I did it in my head, it has to be improved.

  • Really, I put the ID and it didn’t lock. But I still don’t know how to treat the combo...

  • @Diego in the case of "unseen" you can disable the combo and enable when found .

  • @Diego did an update.. demo.

  • Dontvotemedown worked now, I tested your idea and @henriquedpereira’s idea and it worked. Thank you very much!

  • @Diego quiet, anything we are there.

1


In case the best way is not to pass id for <option> and yes to the <select>, and in the code you arrow the values, you pass the select id with the value.

Your html:

<select name="situacao" id="situacao">
  <option value="ATIVO">ATIVO</option>
  <option value="INATIVO">INATIVO</option>
</select>

Call of the js:

document.getElementById("situacao").value = "ATIVO";
  • 1

    What do you mean? You can show me an example?

  • I edited the answer.

  • In fact to tag option may have id yes. Maybe OP has another use for these ids.

  • 1

    I expressed myself badly, edited the answer.

  • 1

    It worked, now set the values. Thank you!!

Browser other questions tagged

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