Insert combobox data into a SELECT

Asked

Viewed 2,883 times

3

Good afternoon!

I have the following problem, I have to withdraw reports from a certain database where I should select specific employees, the same should be selected from a combobox:

<select name="usuario" id="usuario">
    <option value="" disabled="disabled" selected="selected">Selecione o Usuário</option>
    <option>funcionario 1</option>
    <option>funcionario 2</option>
    <option>funcionario 3</option>
    </select>

I want that when selecting an employee, it is sent to the following query:

($result = $mysqli->query("SELECT * FROM tabela WHERE usuario='$funcionario';"))

Should I do this with json? early thanks.

Updating:

$(document).ready(function(){
    $("#usuario").on("change", function(){
        $.ajax({
            url        : 'sql.php',
            type       : 'POST',
            cache      : false,
            dataType   : 'json',
            data       : { 'usuario' : $("#usuario").val() },
            error      : function(){
                alert('Erro ao tentar a ação!');
            },
            success    : function( dados ){ 
                console.log(dados);
            }
        });
    });
}); 
<select name="usuario" id="usuario">
    <option value="" disabled="disabled" selected="selected">Selecione o Usuário</option>
    <option>funcionario 1</option>
    <option>funcionario 2</option>
    <option>funcionario 3</option>
    </select>

`

and the SQL:

$usuario = array("usuario" => array(array("codigo"=>"funcionario 1", "nome"=>"funcionario 1"), array("codigo" => "funcionario 2", "nome"=>"funcionario 2"), array("codigo"=>"funcionario 3","nome"=>"funcionario 3")));  

                    echo json_encode($usuario);

                    if ($result = $mysqli->query("SELECT * FROM tabela WHERE usuario='$usuario';"))
                    {
                            // exibir os registros se há registros para mostrar
                            if ($result->num_rows > 0)
                            {
                                    // exibir registros em uma tabela

                                    echo "<table border='1' cellpadding='5' cellspacing=0 style=border-collapse: collapse bordercolor='#4B5AAB'>";


                                    // definir cabeçalhos de tabela
                                   echo "<tr> <th>ID</th> <th>Data</th> <th>Hora de entrada</th> <th>Hora de saída</th> <th>Comentário</th>";



                                    while ($row = $result->fetch_object())
                                    {
                                            // cria uma linha para cada registro
                                            echo "<tr>";
                                            echo "<td>" . utf8_encode ($row->id) . "</td>";
                                            echo "<td>" . utf8_encode ($row->data) . "</td>";
                                            echo "<td>" . utf8_encode ($row->hora_entra) . "</td>";
                                            echo "<td>" . utf8_encode ($row->hora_saida) . "</td>";
                                            echo "<td>" . utf8_encode ($row->coment) . "</td>"; 
                                            echo "</tr>";
                                    }

                                    echo "</table>";
  • You need to automatically search or change user. Or you will need to click a button to send?

  • Clicking a button, sending to another page probably.

3 answers

4

Thiago the HTML is wrong, in the tags <option> change the attribute of idfuncionario for value.

JQUERY

$(document).ready(function(){
$("#usuario").on("change", function(){
    $.ajax({
        url        : 'caminho_para_arquivo.php',
        type       : 'POST',
        dataType   : 'json',
        data       : ({ 'usuario' : $("#usuario").val() }),
        error      : function(){
            alert('Erro ao tentar a acao!');
        },
        success    : function( dados ){ 
            alert(dados);
        }
    });
});
});

and in the . php file you put something + or - like this:

SQL

$conn = mysql_connect('localhost', 'root', 'vertrigo') or die('Falha na conexão!');  
mysql_select_db('novo');
$objDados = mysql_query('select codigo from usuario where codigo = "69";', $conn);      
$arr = array();
while($row = mysql_fetch_array($objDados) ){
   array_push($arr, $row['codigo']); //isso inseri dados no final de um array.
}

print json_encode($arr);
  • He is giving the msg of error, what would be the cause of this?

  • if ($result = $mysqli->query("SELECT * FROM tabela WHERE usuario='$_POST['usuario']';")) would that way the SQL?

  • The two things you need to see, one is the URL for the file is going, sometimes it may be that the way is wrong and another thing is to check if your query is working properly. ah! when returning the data insert the variable with the data inside the json_encode function();

  • Would it look that way? $usuario = json_encode(array("usuario" => array(&#xA; array("codigo" => "funcionario 1", "nome" => "funcionario 1"),&#xA; array("codigo" => "funcionario 2", "nome" => "funcionario 2"),&#xA; array("codigo" => "funcionario 3", "nome" => "funcionario 3")))); I believe the a URL be correct. ;(

  • Almost that Thiago, actually you instance that Array the variable and passes it as parameter. So: $usuario = array(&#xA; "usuario" => array( &#xA; array(&#xA; "codigo" => "funcionario 1", &#xA; "nome" => "funcionario 1"&#xA; ), &#xA; array(&#xA; "codigo" => "funcionario 2", &#xA; "nome" => "funcionario 2"&#xA; ), &#xA; array(&#xA; "codigo" => "funcionario 3", &#xA; "nome" => "funcionario 3"&#xA; )&#xA; )&#xA;);&#xA;&#xA;echo json_encode($usuario);

  • Bah, I can’t do it myself, I’ll update the question with my code.

  • Thiago, open the Firefox element inspector, go to the tab Console refresh the page and do the whole process again and pay attention to what is the error that returns in the console and send me

  • POST sql.php the result is this.

  • One moment I’m testing here.

Show 4 more comments

3

It is important that you set the user id in the option element when you build select HTML, so you can use the change event with jQuery to make a new request every time a new select option is selected. It is more recommended to use JSON.

You can see an example of how you should post your code here:

$("#usuario").on('change', function(){
   var usuario = $("#usuario option:selected" );
    alert("http://meusite.com/api/v1/usuario?id=" + usuario.attr('idusuario'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="usuario" id="usuario">
    <option value="" disabled="disabled" selected="selected">Selecione o Usuário</option>
    <option idusuario="1">funcionario 1</option>
    <option idusuario="2">funcionario 2</option>
    <option idusuario="3">funcionario 3</option>
</select>

2

Code of the Codepen

/*
	Dropdown with Multiple checkbox select with jQuery - May 27, 2013
	(c) 2013 @ElmahdiMahmoud
	license: http://www.opensource.org/licenses/mit-license.php
*/ 

$(".dropdown dt a").on('click', function () {
          $(".dropdown dd ul").slideToggle('fast');
      });

      $(".dropdown dd ul li a").on('click', function () {
          $(".dropdown dd ul").hide();
      });

      function getSelectedValue(id) {
           return $("#" + id).find("dt a span.value").html();
      }

      $(document).bind('click', function (e) {
          var $clicked = $(e.target);
          if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
      });


      $('.mutliSelect input[type="checkbox"]').on('click', function () {
        
          var title = $(this).closest('.mutliSelect').find('input[type="checkbox"]').val(),
              title = $(this).val() + ",";
        
          if ($(this).is(':checked')) {
              var html = '<span title="' + title + '">' + title + '</span>';
              $('.multiSel').append(html);
              $(".hida").hide();
          } 
          else {
              $('span[title="' + title + '"]').remove();
              var ret = $(".hida");
              $('.dropdown dt a').append(ret);
              
          }
      });
body {  
    font: normal 14px/100% "Andale Mono", AndaleMono, monospace;
    color:#fff;
    padding: 50px;
    width: 300px;
    margin: 0 auto;
  background-color: #374954;
  
} 
a {
    color:#fff;
}
.dropdown dd, .dropdown dt {
    margin:0px;
    padding:0px;
}
.dropdown ul {
    margin: -1px 0 0 0;
}
.dropdown dd {
    position:relative;
}
.dropdown a, 
.dropdown a:visited {
    color:#fff;
    text-decoration:none;
    outline:none;
    font-size: 12px;
}
.dropdown dt a {
    background-color:#4F6877;
    display:block;
    padding: 8px 20px 5px 10px;
    min-height: 25px;
    line-height: 24px;
    overflow: hidden;
    border:0;
    width:272px;
}
.dropdown dt a span, .multiSel span {
    cursor:pointer;
    display:inline-block;
    padding: 0 3px 2px 0;
}
.dropdown dd ul {
    background-color: #4F6877;
    border:0;
    color:#fff;
    display:none;
    left:0px;
    padding: 2px 15px 2px 5px;
    position:absolute;
    top:2px;
    width:280px;
    list-style:none;
    height: 100px;
    overflow: auto;
}
.dropdown span.value {
    display:none;
}
.dropdown dd ul li a {
    padding:5px;
    display:block;
}
.dropdown dd ul li a:hover {
    background-color:#fff;
}
button {
  background-color: #6BBE92;
  width: 302px;
  border: 0;
  padding: 10px 0;
  margin: 5px 0;
  text-align: center;
  color: #fff;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="dropdown"> 
  
    <dt>
    <a href="#">
      <span class="hida">Select</span>    
      <p class="multiSel"></p>  
    </a>
    </dt>
  
    <dd>
        <div class="mutliSelect">
            <ul>
                <li>
                    <input type="checkbox" value="Apple" />Apple</li>
                <li>
                    <input type="checkbox" value="Blackberry" />Blackberry</li>
                <li>
                    <input type="checkbox" value="HTC" />HTC</li>
                <li>
                    <input type="checkbox" value="Sony Ericson" />Sony Ericson</li>
                <li>
                    <input type="checkbox" value="Motorola" />Motorola</li>
                <li>
                    <input type="checkbox" value="Nokia" />Nokia</li>
            </ul>
        </div>
    </dd>
  <button>Filter</button>
</dl>

   /*
Dropdown with Multiple checkbox select with jQuery - May 27, 2013
(c) 2013 @ElmahdiMahmoud
license: http://www.opensource.org/licenses/mit-license.php
*/ 

$(".dropdown dt a").on('click', function () {
      $(".dropdown dd ul").slideToggle('fast');
  });

  $(".dropdown dd ul li a").on('click', function () {
      $(".dropdown dd ul").hide();
  });

  function getSelectedValue(id) {
       return $("#" + id).find("dt a span.value").html();
  }

  $(document).bind('click', function (e) {
      var $clicked = $(e.target);
      if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
  });


  $('.mutliSelect input[type="checkbox"]').on('click', function () {
    
      var title = $(this).closest('.mutliSelect').find('input[type="checkbox"]').val(),
          title = $(this).val() + ",";
    
      if ($(this).is(':checked')) {
          var html = '<span title="' + title + '">' + title + '</span>';
          $('.multiSel').append(html);
          $(".hida").hide();
      } 
      else {
          $('span[title="' + title + '"]').remove();
          var ret = $(".hida");
          $('.dropdown dt a').append(ret);
          
      }
  });
   <dl class="dropdown"> 
  
<dt>
<a href="#">
  <span class="hida">Select</span>    
  <p class="multiSel"></p>  
</a>
</dt>
  
<dd>
    <div class="mutliSelect">
        <ul>
            <li>
                <input type="checkbox" value="Apple" />Apple</li>
            <li>
                <input type="checkbox" value="Blackberry" />Blackberry</li>
            <li>
                <input type="checkbox" value="HTC" />HTC</li>
            <li>
                <input type="checkbox" value="Sony Ericson" />Sony Ericson</li>
            <li>
                <input type="checkbox" value="Motorola" />Motorola</li>
            <li>
                <input type="checkbox" value="Nokia" />Nokia</li>
        </ul>
    </div>
</dd>
  <button>Filter</button>
</dl>

Browser other questions tagged

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