Ajax to make select in bank does not work in new line

Asked

Viewed 173 times

0

I am having difficulty in the following situation, when generating a new table row my Ajax code to make a select in the database does not work. Follow the image below to clarify any doubts:

inserir a descrição da imagem aqui Page:

<div class="form-group">
   <label class="control-label col-lg-4">Víncular Bolsistas:</label>
   <div class="control-label col-lg-9 col-lg-offset-1">
      <div class="form-horizontal">
         <div class="table-responsive">
            <table class="table table-bordered table-striped table-highlight">
               <thead>
                  <div class="row">
                     <th class="col-xs-5 col-sm-5 col-md-5 col-lg-5">Nome</th>
                     <th class="col-xs-4 col-sm-4 col-md-4 col-lg-4  ">Vinculo</th>
                     <th class="col-xs-2 col-sm-2 col-md-2 col-lg-2">Horas</th>
                     <th class="col-xs-1 col-sm-1 col-md-1 col-lg-1"></th>
                  </div>
               </thead>
               <tbody id="tabelaCorpo">
                  <tr id="linhaParaClonar">
                     <td>
                        <select class="bolsista form-control" name="bolsista[0]"></select>
                     </td>
                     <td>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="1">Bolsista</label>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="2">Voluntário</label>
                     </td>
                     <td>
                        <div class=" col-lg-12">
                           <select class="form-control" name="horas[0]">
                              <option value="02:00:00">2</option> 
                              <option value="06:00:00">4</option>
                              <option value="08:00:00">8</option>
                              <option value="16:00:00">16</option>
                           </select>
                        </div>
                        <!-- <input type="number" name="horas[0]" class="form-control" /> -->
                     </td>
                     <td>
                        <!-- <button onclick="removerLinha()" class="glyphicon glyphicon-remove"></button> -->
                     </td>
                  </tr>
               </tbody>
            </table>
            <div class="col-sm-offset-8">
               <input type="button" onclick="clonarLinha()" value="Adicionar" id="adcLinha" class="btn btn-success">
            </div>
         </div>
      </div>
   </div> 
</div>
</div>
</div>
<!--     </div> -->
<div class="row" id="box-cinza-inferior">
   <div class="col-lg-offset-1 col-sm-2">
      <a href="menu-extensao.php" class="btn btn-success" onClick="formVazio();">Voltar</a>
   </div>
   <div class="col-lg-offset-10" >
      <button type="submit" class="btn btn-success">Concluir</button>
   </div>
</div>
</form>
</div>

Javascript code to add line:

function clonarLinha() {
   if (x <= campos_max) {
       $('#tabelaCorpo').append('<tr id="linhaClonada">\
         <td id="atualizarBolsista">\
              <select class="bolsista form-control" name="bolsista[' + x + ']"></select>\
         </td>\
          <td><label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="1">Bolsista</label>\
          <label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="2">Voluntário</label>\
         </td>\
         <td>\
             <div class=" col-lg-12">\
                 <select class="form-control" name="horas[0]">\
                     <option value="02:00:00">2</option> \
                     <option value="06:00:00">4</option>\
                     <option value="08:00:00">8</option>\
                     <option value="16:00:00">16</option>\
                 </select>\
             </div>\
         </td>\
         <td>\
             <input type="button" onclick="removerLinha(this)" class="btnX btn btn-danger" value="X">\
         </td>\
         </tr>');
       x++;
   }
}

Ajax:

// Campo autocomplete que busca no banco o nome do aluno
$('.bolsista').select2({
   placeholder: 'Selecione um aluno',
   ajax: {
      url: '../php/ajaxSelectAluno.php',
      dataType: 'json',
      delay: 250,
      processResults: function (data) {
         return {
            results: data
         };
      },
      cache: true
   }
});

Ajaxselectstudent:

<?php
include ("../classe/conexao.php");
$sql = "SELECT p.id as id, p.nome
FROM pessoa p
JOIN aluno a ON a.aluno_id_pessoa = p.id
WHERE nome LIKE '%".$_GET['q']."%'
LIMIT 10"; 

# WHERE nome LIKE '%".$_GET['q']."%'
$result = $mysqli->query($sql);

$json = [];

while($row = $result->fetch_assoc()){
   $json[] = ['id'=>$row['id'], 'text'=>$row['nome']];
}

echo json_encode($json);
  • Note that on this line <input type="radio" name="vinculo[0] value="2">Voluntário</label> is missing a double quotes in name="vinculo[0].

  • I also believe that you posted the Javascript code to add the wrong line. It doesn’t match the image shown in the question.

  • In line <input type="radio" name="link[0] value="2">Volunteer</label> was missing double quotes when I posted the question, the code was right

  • Corrgido line add code

1 answer

0


I suggest creating a proper function to apply the select2:

function aplicaSelect2(){
   $('.bolsista').select2({
      placeholder: 'Selecione um aluno',
      ajax: {
         url: '../php/ajaxSelectAluno.php',
         dataType: 'json',
         delay: 250,
         processResults: function (data) {
            return {
               results: data
            };
         },
         cache: true
      }
   });
}

This way, each time a row is added, the select2 will be applied to rows added.

Also add the code below to start the select2 page loading:

$(document).ready(function(){
   aplicaSelect2();
});

And finally, call the function aplicaSelect2() when adding a new line:

function clonarLinha() {
   if (x <= campos_max) {

       ...

       x++;
       aplicaSelect2();
   }
}

See working:

var campos_max = 10;   //max de 10 campos
var x = 1;
function clonarLinha() {
   if (x <= campos_max) {
       $('#tabelaCorpo').append('<tr id="linhaClonada">\
         <td id="atualizarBolsista">\
              <select class="bolsista form-control" name="bolsista[' + x + ']"></select>\
         </td>\
          <td><label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="1">Bolsista</label>\
          <label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="2">Voluntário</label>\
         </td>\
         <td>\
             <div class=" col-lg-12">\
                 <select class="form-control" name="horas[0]">\
                     <option value="02:00:00">2</option> \
                     <option value="06:00:00">4</option>\
                     <option value="08:00:00">8</option>\
                     <option value="16:00:00">16</option>\
                 </select>\
             </div>\
         </td>\
         <td>\
             <input type="button" onclick="removerLinha(this)" class="btnX btn btn-danger" value="X">\
         </td>\
         </tr>');
       x++;
       aplicaSelect2();
   }
}

function aplicaSelect2(){
   $('.bolsista').select2({
      placeholder: 'Selecione um aluno',
      ajax: {
         url: '../php/ajaxSelectAluno.php',
         dataType: 'json',
         delay: 250,
         processResults: function (data) {
            return {
               results: data
            };
         },
         cache: true
      }
   });
}

$(document).ready(function(){
   aplicaSelect2();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<div class="form-group">
   <label class="control-label col-lg-4">Víncular Bolsistas:</label>
   <div class="control-label col-lg-9 col-lg-offset-1">
      <div class="form-horizontal">
         <div class="table-responsive">
            <table class="table table-bordered table-striped table-highlight">
               <thead>
                  <div class="row">
                     <th class="col-xs-5 col-sm-5 col-md-5 col-lg-5">Nome</th>
                     <th class="col-xs-4 col-sm-4 col-md-4 col-lg-4  ">Vinculo</th>
                     <th class="col-xs-2 col-sm-2 col-md-2 col-lg-2">Horas</th>
                     <th class="col-xs-1 col-sm-1 col-md-1 col-lg-1"></th>
                  </div>
               </thead>
               <tbody id="tabelaCorpo">
                  <tr id="linhaParaClonar">
                     <td>
                        <select class="bolsista form-control" name="bolsista[0]"></select>
                     </td>
                     <td>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="1">Bolsista</label>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="2">Voluntário</label>
                     </td>
                     <td>
                        <div class=" col-lg-12">
                           <select class="form-control" name="horas[0]">
                              <option value="02:00:00">2</option> 
                              <option value="06:00:00">4</option>
                              <option value="08:00:00">8</option>
                              <option value="16:00:00">16</option>
                           </select>
                        </div>
                        <!-- <input type="number" name="horas[0]" class="form-control" /> -->
                     </td>
                     <td>
                        <!-- <button onclick="removerLinha()" class="glyphicon glyphicon-remove"></button> -->
                     </td>
                  </tr>
               </tbody>
            </table>
            <div class="col-sm-offset-8">
               <input type="button" onclick="clonarLinha()" value="Adicionar" id="adcLinha" class="btn btn-success">
            </div>
         </div>
      </div>
   </div> 
</div>
</div>
</div>
<!--     </div> -->
<div class="row" id="box-cinza-inferior">
   <div class="col-lg-offset-1 col-sm-2">
      <a href="menu-extensao.php" class="btn btn-success" onClick="formVazio();">Voltar</a>
   </div>
   <div class="col-lg-offset-10" >
      <button type="submit" class="btn btn-success">Concluir</button>
   </div>
</div>
</form>
</div>

Browser other questions tagged

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