Pass multiple variables into Ajax function

1

QUESTION REFERENCE TO FACILITATE THE EXAMPLE

I have the following inputs in an HTML (I will show 3, but the actual situation is 20):

          <tr>
              <td>Digite o código:</td>
              <td><input type = "text" id="cod_item" name = "cod_item" size = 10 maxlength =5 placeholder="Código" onChange="getPeca();">
                  <input type = "text" id="desc_item_1" name = "desc_item_1" size = 30 maxlength =30 placeholder="Descrição">
                  <input type = "text" id="qtde_item_1" name = "qtde_item_1" size = 5 maxlength =5 placeholder="Qtde"></td>
          </tr>

          <tr>
              <td>Digite o código:</td>
              <td><input type = "text" id="cod_item_2" name = "cod_item_2" size = 10 maxlength =5 placeholder="Código">
                  <input type = "text" id="desc_item_2" name = "desc_item_2" size = 30 maxlength =30 placeholder="Descrição">
                  <input type = "text" id="qtde_item_2" name = "qtde_item_2" size = 5 maxlength =5 placeholder="Qtde"></td>
          </tr>

          <tr>
              <td>Digite o código:</td>
              <td><input type = "text" id="cod_item_3" name = "cod_item_3" size = 10 maxlength =5 placeholder="Código">
                  <input type = "text" id="desc_item_2" name = "desc_item_2" size = 30 maxlength =30 placeholder="Descrição">
                  <input type = "text" id="qtde_item_2" name = "qtde_item_2" size = 5 maxlength =5 placeholder="Qtde"></td>
          </tr>

The intent is for all of these cod_item to access the query below and display the description in the desc_item field. Example: The user types the code and Ajax returns the description. Go to field 2 type the code and the description appears. The user can enter from 1 to 20.

$sqlRetorno = 'SELECT descricao from pecas WHERE
               cod_peccin = :codItem;';

$resRetorno = $conexao->prepare($sqlRetorno);
$resRetorno->execute(array(
    ':codItem' => $codItem,
));
$retornos = $resRetorno->fetchAll();

In the initial question I have an Ajax but it only works for one item. In this case, how could you make all the fields do the same query and return the description of the entered item independently, without having to make a script for each field?

    
asked by anonymous 26.02.2016 / 19:30

3 answers

1

If I understand correctly, you want to do an ajax query for each field of code that changes, and then fill in the description field with the result of the query.

  

I'm only reproducing snippets of your code to help you understand.

First let's treat your HTML :

  • standardize your page so that each field has an identification number;
  • enter the field code as the argument of the getPeca() function;
  • Make sure each set has a unique code. Look at the example:
    <!-- Bloco do item 1 -->
    <tr>
        <td>Digite o código:</td>
        <td>
            <input type="text" id="cod_item_1" ... onChange="getPeca(1);">
            <input type="text" id="desc_item_1" ... >
            <input type="text" id="qtde_item_1" ... >
        </td>
    </tr>

No Javascript :

  • first create the parameter that will receive the code (ex: id_campo );
  • the parameter variable will be used to concatenate the field name, thus "cod_item_" + id_campo will be converted to cod_item_1 when id_campo is 1 ;
  • When the server responds you can use the reasoning of the previous item to populate the information from the corresponding description field. Again, see the example:
    function getPeca(id_campo) {
        ...
        // aqui o código do campo 'cod_item_{n}' é atribuido a 'codItem'
        var codItem = document.getElementById("cod_item_" + id_campo).value;

        ...
        xmlreq.open("GET", "ProcessaPecaEdicao.php?codItem=" + codItem, true);
        ...
        // durante o retorno do servidor
        if (xmlreq.responseText == "") {

            // Se o retorno for vazio basta gerar o alerta
            alert("Item inexistente! Cadastre antes");
        } else {

            // Aqui recebe os dados do processa.php, abre e aplica nos campos desejados
            var descricao = JSON.parse(xmlreq.responseText);

            // Retornando apenas a descrição referente ao 'cod_item_{n}'.
            document.getElementById("desc_item_" + id_campo).value = descricao;

            document.getElementById("qtde_item_" + id_campo).focus();
        }

        ...
    }

Finally, in the code PHP ( ProcessPageEdicao.php ):

  • this file will be called each time the html block code field ( cod_item_ {n} ) is changed;
  • the query performed here, search 1 specific code ( probably a primary key, right? ), and expect only 1 record in response. So you can use fetch instead of fetchAll ;
  • It is a good practice to use closeCursor to release the connection and allow new queries to be performed. more details
  • Because it is called only to inform a description of a code only ( codItem ), there is not much to program. In the example below, when a code is received, the query is done in the database and returns the description of the code entered;
    // Dados do banco e controle de acesso
    include "js/conn.php";

    // Recebe variavel do index
    $codItem = $_GET["codItem"];

    //Inicia a consulta ao banco, com os dados informados pelo cliente.
    $sqlRetorno = 'SELECT descricao from pecas WHERE
                   cod_peccin = :codItem;';

    $resRetorno = $conexao->prepare($sqlRetorno);
    $resRetorno->execute(array(
        ':codItem' => $codItem,
    ));

    $retornos = $resRetorno->fetch(PDO::FETCH_ASSOC);
    $resRetorno->closeCursor();

    // Pequeno tratamento de erro do retorno.
    $retorno_tratado = ($retornos == false ? '' : $retornos['descricao']);

    // Retorna somente a descrição do código solicitado.
    echo json_encode($retorno_tratado);

I tried to keep your code similar to the original and make it as clear as possible, as you can use a ajax routine to update several fields.

    
03.03.2016 / 01:09
3

There is a problem here:

foreach ($retornos as $retorno) {

     $array = array('desc_item_1'=>$retorno['descricao']);
     echo json_encode($array);
}

You're probably generating a lot of json, but that does not work, otherwise it would look like this:

  

{"desc_item_1": [...]} {"desc_item_1": [...]} {"desc_item_1": [...]} {"desc_item_1": [...]} {"desc_item_1 ": [...]}

The correct thing would be to group in a single array like this:

$retornos = $resRetorno->fetchAll();
$arrayAgrupada = array();

foreach ($retornos as $retorno) {
     $arrayAgrupada[] = array('desc_item_1'=>$retorno['descricao']);
}

echo json_encode($arrayAgrupada);

Now you can use JSON.parse , your result will look something like:

[
    {"desc_item_1": [...]},
    {"desc_item_1": [...]},
    {"desc_item_1": [...]},
    {"desc_item_1": [...]},
]

I'll be honest that I did not understand desc_item_1 , maybe it's increment or is it the bank ID? So do it:

$sqlRetorno = 'SELECT id, descricao from pecas WHERE
           cod_peccin = :codItem;';

$retornos = $resRetorno->fetchAll();
$arrayAgrupada = array();

foreach ($retornos as $retorno) {
     $arrayAgrupada[$retorno['id']] = $retorno['descricao'];
}

echo json_encode($arrayAgrupada);

Result:

{
   "1": "...",
   "2": "...",
   "4": "..."
}

And in Javascript this:

var dados = JSON.parse(xmlreq.responseText);

ids.forEach(function (id) {
    var currentId = "desc_item_" + id;
    document.getElementById(currentId).value = dados[currentId];
});
    
29.02.2016 / 01:42
-1

Do not give the fish, teach fishing

  • First you will need to add the 20 inputs in your html, giving a different id for each of them

    2.Add query selectors for each input in your javascript

  • In your php code add a $ _GET for each different input

  • If you want to get this past data and send it to the mysql query, add:

  • $sqlRetorno = 'SELECT descricao from pecas WHERE
                   cod_peccin = :codItem,
                   cod_peccin2 = :codItem,
                   cod_peccin = :codItem;';//adicione do 1 ao 20 em diante
        
    29.02.2016 / 01:32