How to get the value dynamically from a select

1

Hello everyone, can anyone help me with this little problem that I have? Since I'm not very good at javascript. I want to get the value of a select dynamically and according to the selected select do a dynamic SQL lookup in project made in pure php.

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);
    
asked by anonymous 16.12.2014 / 19:23

2 answers

2

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 work out something on account so you begin to understand manipulating events by javascript.

This example PHP file is using PDO if you need to adapt to what you are accustomed to. The return of this routine is a JSON with all records retrieved from the database. Take a lookup if you do not know about JSON.

Do not 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>
    
16.12.2014 / 21:02
1

Well, then the question we have is: How to get select values from 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 without leaving it at all, this would be an example similar to yours.

It's very simple, basically we need 2 files index.html and cadastro.php

full code: download full code

index.html is simply an HTML file with the common form that we already know the difference is in the 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 everything is finished, type is the way data is sent be GET

cadastro.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 at:

jquery.com

ajax function

    
16.12.2014 / 20:12