Pass multiple variables in Ajax function

Asked

Viewed 556 times

1

REPEATED QUESTION 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 intention is all these cod_item access the query below and display the description in the field desc_item. Example: The user enters the code and Ajax returns the description. Go to field 2 enter the code and the description appears. User can type from 1 up 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 works only for one item. In this case, how could all fields do the same query and independently return the description of the entered item, without having to make a script for each field?

  • Want to send one to one or all in the same ajax? insert one piece by input, or several in the same input? In case there are several inputs you can all be inside the same table?

  • The inputs are all on the same page and the fields in the table I will save as well. Enter one code at a time, but all 20 are on the same form.

  • vc can pass all variables at once by using serialize, with the syntax: formName.serialize();

  • you cannot do ajax by jquery?

  • Can you give me an example of how to do that?

  • http://api.jquery.com/jquery.post/ this is a way to ajax with jquery, which is easier than with pure javascript

  • https://api.jquery.com/serialize/ serialize documentation...

  • Jesus Diego even you are using snippet stack ("code snippet") no need :/ - The snippet stack is obviously used to run javascript, html and css, that is front-end, there is no reason to use stacksnippet to put php, c++, java, c#, this will never run PHP. If only to display code use normal markup ("code sample" or Ctrl+k).

  • It was wrong @Guilhermenascimento

  • @Alexandremartinsmontebelo I will try to turn this idea of yours into a solution, if I warn you to answer the question and win the reward.

  • beauty! using this jquery post function, you do ajax in a safe way and in passing the parameters of this function, you only use serialize to then do as if it were a Ubmit on the page, only using ajax ;)

Show 6 more comments

3 answers

3

There’s a problem here:

foreach ($retornos as $retorno) {

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

You’re probably generating several json, but that doesn’t work because otherwise it would be a result like this:

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

The correct would be to group in 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 be something like :

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

I’ll be honest I didn’t understand the desc_item_1, maybe it’s increment or is the bank ID? Do so then:

$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);

Upshot:

{
   "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];
});
  • Good morning. Actually, the field in the bank is unique, I used this nomenclature of desc_item_1 up to 20 in the inputs you would like to feed into html. I’m trying to understand your answer, but basically my problem is that every input the user would pass the code is different, but I need to use the same query for everyone, got it?

  • @Diego will be an ajax for each field?

  • Exactly. In a solution I found here, I would have to create 20 js, one for each input, 20 PHP to process the request, declare 20 functions in the body onload()......I don’t believe it’s right

  • @Diego then my answer is just a request with js, I do not know how is your SELECT, but changing it can bring all 20 results with the code I posted, to on mobile once I get I edit the answer, only informs me the SELECT query

  • Ok! This is in Procesapecaedicao.php the query I use is the variable I pass, in case one only. Thank you very much for the help.

  • @Diego I will admit that your code is very confusing, no offense rs, cod_peccin is the ID of each product? Inputs are generated dynamically?

  • cod_peccin is a column that has the entry code in the table. The inputs I’m doing on the arm, as I don’t know any other way I’m naming that way codItem, codItem1, codItem2....

  • @Diego is what’s confusing, each input is a table item or not?

  • No. Each input has to access the table with the value the user passes. The query will be 20 times equal if the user enters 20 items.

  • @Diego if understood the query is made when clicking on the input?

  • Exact!!! Search the item and brings the description.

Show 6 more comments

1


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

I’m only reproducing fragments of your code, to help you understand.

First we’ll take care of your HTML:

  • Program your page so that each field has an identification number;
  • insert field code as function argument getPeca();
  • make sure that each set has a unique code. Note 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>

In the Javascript:

  • first create the parameter that will receive the code (eg: id_campo);
  • the parameter variable will be used to concatenate the field name in this way, "cod_item_" + id_campo will be converted into cod_item_1 when the id_campo for 1;
  • When the server responds you can use the reasoning of the previous item to fill in 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 (Parsing.php):

  • this file will be called each time the code field (cod_item_{n}) a block of html is changed;
  • the query performed here, search 1 specific code (probably a primary key, right?), and expects only 1 record as answer. Therefore you can use fetch instead of fetchAll;
  • is a good practice you use the closeCursor to release the connection and allow new queries to be performed. more details
  • by being called only to inform a description of a code only (codItem), does not have 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 informed;
    // 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 routine ajax that update several fields.

  • That’s exactly what I couldn’t do. Thank you so much for your help!

  • Ah, I only have one question here: if (xmlreq.responseText == "") { // If the return is empty just generate the alert Alert("Non-existent item! Register before"); He is not entering here, goes straight to Focus in quantity, would you know what could be wrong? In firebug the return appears only null

  • 1

    @Diego, I added a small error correction to the code. Basically the Fetch returns false when there is no record in the bank. I had not dealt with it.. my bad.

-1

Don’t give the fish, teach them to fish

  1. First you’ll need to add the 20 inputs to your html, giving a different id to each of them

    2.Add query selectors to each input in your javascript

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

  3. If you want to take this past data and mandalas in 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
  • Just a hint WHERE does not wear comma ,, try to use IN(..., ...,) within WHERE (although I don’t understand your intention in SELECT)

  • As query selectors?

  • I already programmed in php, I can’t remember whether to use or not comma, so I did as an example

Browser other questions tagged

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