How to take the value dynamically from a select

Asked

Viewed 13,354 times

1

Hello guys can someone give a force in this problem I caught? Since I’m not very good in javascript. To want to take the value of a select dynamically and according to the selected select do a dynamic SQL search in pure php project.

echo '<select name="op">';
echo  '<option value="Rede">Rede</option>';
echo   '<option value="Suport">Suporte</option>';
echo   '<option value="Backend">BackEnd</option>';
echo   '<option value="FrontEnd">FrontEnd</option>';
echo '</select>';

$qq = $_POST['op'];
$q3 = "SELECT * FROM `lcm_author` WHERE `sector` LIKE '$qq'";
$query3 = lcm_query($q3);
  • You can use AJAX for this... use the event $("select").change(function(){}); select and fire an AJAX call to search the data dynamically. This with Jquery, just for the record. If you already have something from javascript, post together in the question to see.

  • In fact I have nothing in javascript for this feature, the big question is that I do not know how to do it ! I tried to take the example you have on the internet about (state/city search dynamically) to have a base, but I still can’t make the right changes.

  • Give a search in AJAX (asynchronous request) and Jquery, with this you can solve your question.

2 answers

3


JS file

$("select").change(function(){ //Evento quando o elemento select é alterado.
    $.ajax({
        url: "filtrar.php", //Página que fará a busca no banco de dados
        type: 'POST',
        data: { filtro: $(this).val() }, //Variáveis postadas para o arquivo definido
        complete: function (e, xhr, result){
            if(e.readyState ==4 && e.status ==200){
                try{
                    var Obj = eval("("+ e.responseText + ")");//combo os
                }
                catch(err){
                }
                if(Obj != null){
                    if(Obj.msg == '1'){
                        console.log(Obj);
                    } else {
                        console.log('Nenhum registro retornado');
                    }
                }
            }
        }
    });
});

PHP file

    $setor = $_POST['filtro'];

    $retorno = array();

    $sql = "SELECT ... WHERE sector LIKE (:filtro);";

    $vars = array(":filtro"=>"%{$setor}%");

    $stmt = $pdo->prepare($sql);

    foreach($vars as $index => $value){
        $stmt->bindValue($index,$value);
    }

    if($stmt->execute()){
        $count = $stmt->rowCount();
        $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
        $rows['msg'] = '1';
        $rows['length'] = $count;

        $i = 0;
        while($i < $count){
            foreach($rows[$i] as $index => $value){
                $rows[$i]->$index = ($value);
            }
            $i++;
        }

        return json_encode($rows,true);
    } else {
        return json_encode(array("msg" => '0'),true);
    }

Adriano, use base and try to elaborate something on your own so you start to understand how to handle events by javascript.

This example PHP file is using PDO, if you need to adapt to what you are used to. The return of this routine is a JSON with all the records recovered from the database. Do a search if you do not know about JSON.

Don’t forget to include the Jquery library in your code header, otherwise none of this will work

Jquery

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
  • you took my lock! "url" from ajax I can put the file itself (calling itself)? Since everything will stay in a single file! Or I will have to separate even ?

  • 1

    For you to use the same page for everything, you will have to put some Ifs for when the AJAX request is called, only the printing of the recovered data from the database may appear, that would be echo json_encode(). But I recommend that you have one file with HTML another with JS and another with the search in the database, so it is much more organized and you do not need to be making unnecessary Ifs to run only one piece of code when AJAX is called.

1

Well then the question we have is: How to get select values from the PHP server without "refreshing" the page? The answer is: Use AJAX, there are some ways to use Ajax and in my opinion the easiest and most compatible is with jQuery.

Imagine that we have a login/registration page and we want it to send the information to the server more without leaving it under any circumstances, this would be an example similar to yours.

It’s very simple, basically we need 2 files index.html and cadastre.php

complete code: download full code

index.html is simply an HTML file with the common form we already know the difference is in the function ajax

var campos = {nome: "Joao", idade: 32};
$.ajax({
            data: campos,// dados que serão enviados para o servidor
            url: "cadastro.php", // url a buscar sem fazer refresh (ajax)
            type: "POST", // método de envio dos dados (GET,POST)
            dataType: "html", // como será recebida a resposta do servidor (html,json)
            success: function(data){ // função que tras a resposta quando tudo der certo
               alert(data);
            },
            error: function(){
                alert("problema ao carregar a solicitação");
            }
        });

fields is the variable with the data to be sent, Success is the function that is called when all is over, type is the data sending mode that can also be GET

php. You simply take the fields, do whatever you want with them and print out an answer

<?php
echo "você enviou os campos: <br/>";
print_r($_POST);

More details on:

jquery.com

ajax function

  • In my form "<form action="pop_up_upd.php" method="post">" has several select within it this is one of them, the form calls another php file that has the database select.

  • So in theory you’d be right, have you ever tried to echo the $qq variable to see if the value is coming? , I think the problem may be your SQL try to change the value from $Q3 to $Q3 = "SELECT * FROM lcm_author WHERE sector LIKE '%$qq%'";

  • The big problem is that you have to change the select option when you change it. That’s the big question.

  • 1

    @deFreitas , I believe that Adriano’s problem is not the operation of the filter. But he wants to make the filter dynamic, without reloads. So he has to use AJAX to change the page content dynamically when a new value is selected in SELECT. That’s it Adriano?

  • That’s right! @Danielribeiro

  • Well I think I got it @Adrianocarvalho take a look at the answer I rephrased and see if it solves your problem

Show 1 more comment

Browser other questions tagged

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