Recover select value via JS and play in PHP variable

Asked

Viewed 8,670 times

0

I need to take the chosen value of select and play in one query, how to do? In practice (following the example) I choose in select a driver and this select will return below all the records referring to this driver, maybe the fields can be date of the trip, vehicle, etc. (is just an example) all without a Ubmit button or any other.

I have the following select list:

<select name="regiao" onchange="run()" id="regiao">
 <option value="0" selected="selected">Escolha a Região</option>
 <?php 
 //listar regioes
    $db->select_pdo("SELECT * FROM regiaos order by indOrdem ASC"); 
    foreach($db->result as $value){
      echo '<option value="'.$value['idRegiao'].'">'.$value['txtDescricao'].'</option>';
    } 
 ?>
</select>

E o Javascript:

<script>
   function run() {
    document.getElementById("rstregiao").value = document.getElementById("regiao").value;
   }
</script>

E o resultado (que imprime o html c o valor correto, porém eu precisaria do valor sem o html para rodar a variável na query): 

<?php 
  $regiaos = '<input type="text" id="rstregiao" placeholder="valor">';
    echo $regiaos; 
    //listar redecredenciadas 
    $db->select_pdo("SELECT * FROM redecredenciadas WHERE idRegiao = '$regiaos' order by txtNome ASC"); 
    foreach($db->result as $value){
      unset($credenciada);  
      $credenciada = $value['txtNome'];
        echo $credenciada; }
?>

----->

Now I have the following situation:

COMBO updates the page of the query, the result returns and is printed, but in printing I am not able to make the format of the loop is consistent with the table, below my files for who can help, and of course, @Thomas who has helped and a lot! (Thank you very much)

--> JAVASCRIPT

<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
        $(document).ready(function(e) {
            $("body").delegate("#regiao", "change", function(data){

                //Pegando o valor do select
                var valor = $(this).val();
                //Enviando o valor do meu select para ser processado e
                //retornar as informações que eu preciso
                $("#conteudo").load("regiaos.php?parametro="+ valor);

            });
        });
</script>

--> QUERY PAGE

<?php
include ("conn.php");

$parametro = $_GET['parametro'];
$db->select_pdo("SELECT * FROM redecredenciadas WHERE idRegiao = '$parametro' ORDER BY idRegiao ASC");
    foreach($db->result as $value){
    echo '<tr>
            <td>- '.$value['txtNome'].'</td>';
    }
?>

--> PAGE WITH PRINTED RESULT (with the wrong formatting due to the TAG that needs to have the

Name of the Accredited Unit Active AOP POP APC HO PSI PSO H PS M PA HP AMB PS Inf

--> THE RESULT ON THE SCREEN

Name of Accredited Unit | Active |AOP|POP|APC|HO|PSI|PSO|H|PS|M|PA|HP|AMB|PS Inf - unit 01 | chk | ch|ch |ch |ch|ch |ch |c|ch|c|ch|ch|ch | chk - unit 02 - unit 03 etc... and chechbox (chk) are not inside the loop the units are in a single cell (I said it was ridiculous)

Thank you

  • Welcome to Stack Overflow. And what have you done so far? Look deeper into your question. Read [Ask] and take a [tour].

1 answer

1


Partner, I see 2 solutions to this:

1st - When calling the run() function in Javascript, take the value of your select and use it in a redirect passing it as parameter:

var valor = document.getElementById("regiao").value;    
window.location = "pagina.php?parametro=valor"

2nd - In particular, I consider this second solution the best: Use jQuery. You can use $.get(), $.post(), $.ajax() or use . load(). So you can do your query without using refresh().

Below is an example of a code:

index php.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>

        <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
        <script>
        $(document).ready(function(e) {
            $("body").delegate("#regiao", "change", function(data){

                //Pegando o valor do select
                var valor = $(this).val();
                //Enviando o valor do meu select para ser processado e
                //retornar as informações que eu preciso
                $("#conteudo").load("query.php?parametro="+ valor);

            });
        });
        </script>
    </head>

<body>
<select name="regiao" id="regiao">
    <option value="1">Marcos da Silva</option>
    <option value="2">João da Silva</option>
    <option value="3">Roberto da Silva</option>
</select>

<div id="conteudo"></div>
</body>
</html>

query.php

<?php

$parametro = $_GET['parametro'];

//Aqui você pode fazer a sua query, e buscar os dados de um banco de dados

?>
<table>
    <thead>
        <tr>
            <th>Nome</th>
            <th>Idade</th>
            <th>Próxima Viagem</th>
            <th>Veículo</th>
        </tr>
    </thead>
    <tbody>
        <?php if ($parametro == 1): ?>
            <tr>
                <td>Marcos da Silva</td>
                <td>30</td>
                <td>01/02/2015</td>
                <td>Fiorino</td>
            </tr>
        <?php endif; ?>
        <?php if ($parametro == 2): ?>
            <tr>
                <td>João da Silva</td>
                <td>45</td>
                <td>21/02/2015</td>
                <td>Sprinter</td>
            </tr>
        <?php endif; ?>
        <?php if ($parametro == 3): ?>
            <tr>
                <td>Roberto da Silva</td>
                <td>25</td>
                <td>10/03/2015</td>
                <td>Doblo</td>
            </tr>
        <?php endif; ?>
    </tbody>
</table>

In the query.php file you make your query and bring the data and format as you wish. See that each time you change the value of select, it calls the query.php and executes what I want.

I hope I’ve helped =)

  • Thomas, thanks for the return, but is that the line $regiaos = '<input type="text" id="rstregiao" placeholder="value">'; echo $regiaos; in this echo of the variable $regiaos comes the correct number within an html (input field) I don’t want to, how do I take this html and just take the number? I do not know if I was clear, but this is exactly what I need, because this number play in the query on the same page, worth!

  • The problem is that PHP and Javascript work differently: PHP needs to be sent to the server to interpret, and Javascript runs in the browser. With this, each time you select a record in SELECT, you are required to submit that page. Then you could use the first solution, and exchange this line of $regiaos = '<input..., for $regiaos = $_GET['parameter']. The advantage of using jQuery is that you don’t need to submit the page, each time you choose a value in SELECT, it automatically executes your query.

  • I know that each one rotates in a "tip", and I thought that there was a solution to this, and after reading your answer I was thinking more still that it is possible (rs), Oce could pass on this code for me to try to run here, because I was confused by so many parts (very well explained) examples, you know what I mean? Tks? > - I prefer to use Jquery (although not good enough) and avoid sending to another page (if possible)

  • I edited my answer, test these 2 codes and see if this is what you wanted.

  • This is exactly what I needed. It already used a script and an attached page to fill a sequence of combos, but I thought it could be in a single page the solution of this issue. It was very worth your help and I hope the code will serve others! Thank you!

  • I think you can even do it on one page, if in . load() you pass the same page you are using, passing some parameters. However, I believe it is not a good practice, since the interesting thing is that you separate functions. I’m glad I was able to help =) Vlw!

  • and other collaborators, now I need to print the results but the problem is to work with the <tr> and <td> because referencing the tag id="content" I am not able to correctly format the line break, how to post here the codes correctly for your view? Thank you

  • I suggest you edit your question, or create a new one with the codes you are using and what you want to do! =)

  • I made changes to your text including everything but does not appear....

  • yes, I saw, I had to refuse due to the rules of the site. In the answers, they should only contain ANSWERS. Questions and other problems should be made via comment or with another question.

  • Sorry, I’m new here, but how do I ask again without losing the bond here and your collaboration? Here in the comment I can not provide as many lines of code. Thank you

  • No problem, I’m still learning. Edit your question by putting your new problem at the end, and then I edit my answer, or add a new answer.

  • I’ve already changed my question, thank you!

  • Eduardo, post the code of the HTML page where your combobox is

  • Hello @Thomas and everyone, sorry it took me so long to read your request. I will post below:<select name="regiao" id="regiao"> <option value="0" Selected="Selected">Choose Region</option> <? php //list regions $db->select_pdo("SELECT * FROM regiaos order by indOrdem ASC"); foreach($db->result as $value){ ? > <Strong> <? php echo '<option value="'. $value['idRegiao']. '">'. $value['txtDescription']. '</option>';} ? > </Strong> </select>, this select works OK, result OK, the move is that HTML

  • page is empty, but the result on the page is visible. then the problem would be how to use the values of the checkboxes selected from this result?

  • Hello again, I stopped this code because what happens: in the html page all combos are filled in this goes and comes, however the result that returns from the JS can no longer be used, it is printed on the page but is not part of the code, so much so that viewing the code of the page you do not see this content, only the Tags where it should appear. It’s the expected scenario when we work with JS and PHP. I think there’s no way out of this, is there? Thanks

Show 12 more comments

Browser other questions tagged

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