How to pass via POST Javascript information to PHP

Asked

Viewed 81 times

-2

I have a select which is assembled via database query.

<?php
      $tl_rel = "";
      $arg = array("select"=>"*","tabela"=>"TAB_RELATORIOS","where"=>"where login='{$_SESSION['login']}'");
      $obj_rel = $obj_pdo->getConsulta($arg);
      $tl_rel = count($obj_rel);
?>
    <div class="form-row">
      <div class="form-group col-md-4">
        <label class="control-label" for="opcoes">Relatórios Salvos</label>
        <select class="custom-select" id="opcoes" name="opcoes" onclick="mostra(this);">
          <option value="0" selected>Selectione</option>
<?php
            for($i=0; $i < $tl_rel; $i++){
                print "<option value='{$obj_rel[$i]->TABELAS}'>{$obj_rel[$i]->NOME}</option>";
            }
?>

I need to get the text from option user selected to mount a second select, also via database.

I tried to do this via Ajax through the code below, but it displayed the whole HTML in the console.

function mostra(lista){
    var x = lista.options[lista.options.selectedIndex];
    var nome = x.text;
    if(lista.value != "0"){
        $("#Lista2").prop("hidden", true);
        $.ajax({
            type: 'POST',
            url: 'relatorios.php',
            cache: false,
            data: { 'tabela': nome },
            success: function(retorno){
                alert(retorno);
            }
        });
    }else{
        $("#Lista2").prop("hidden", false);
    }
}

There is a way to do this, without me having to display all the HTML as an answer?


This is all the code.

<!doctype html>
<html lang="pt-br">
<head>
<title>Relatório de Follow Up Honda</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="relatorio" content="relatorio_prof_honda">
<link rel="shortcut icon" href="../imagens/logo-pequeno.png">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style>
    body { background-image: url("../imagens/fundo.png"); }
    * { box-sizing: border-box; font-size: 10pt; }
    .corpo { width: 45%; height: 320px; margin: 150px auto auto 100px; padding: 5px; }
    .dropdown-item:hover{ color:#fff; text-decoration:none; background-color:#28a745; border-color:#28a745 }
    li { width: 90px; text-align: center; }
    li:hover { border-bottom: 1px solid #fff; }
</style>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="../java/jquery.selectlistactions.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: rgba(0,0,0,0.8)">
  <div class="collapse navbar-collapse" id="navbarToggler">
    <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
      <li class="nav-item">
        <a class="nav-link" href="index.php">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="novo.php">Novo</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="protocolo.php">Protocolo</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="relatorios.php">Relatórios</a>
      </li>
    </ul>
  </div>
</nav>

<form action="" method="post" name="form" id="form" target="_blank">
  <div class="corpo">
    <div class="form-row">
      <div class="form-group col-md-5">
        <label for="dt_ini">De</label>
        <input type="date" class="form-control" id="dt_ini" name="dt_ini" required autofocus />
      </div>
      <div class="form-group col-md-2">
        <label for=""> </label>
      </div>
      <div class="form-group col-md-5">
        <label for="dt_fim">Até</label>     
        <input type="date" class="form-control" id="dt_fim" name="dt_fim" value="<?php print date('Y-m-d'); ?>" required />
      </div>
    </div>

<?php
      $tl_rel = "";
      $arg = array("select"=>"*","tabela"=>"TAB_RELATORIOS","where"=>"where login='{$_SESSION['login']}'");
      $obj_rel = $obj_pdo->getConsultaDI($arg);
      //var_dump($obj_rel);
      $tl_rel = count($obj_rel);
?>
    <div class="form-row">
      <div class="form-group col-md-4">
        <label class="control-label" for="opcoes">Relatórios Salvos</label>
        <select class="custom-select" id="opcoes" name="opcoes" onclick="mostra(this);" onChange="DesmarcarOp();SelecaoRelatorio();">
          <option value="0" selected>Selectione</option>
<?php
            for($i=0; $i < $tl_rel; $i++){
                print "<option value='{$obj_rel[$i]->TABELAS}'>{$obj_rel[$i]->NOME}</option>";
            }
?>
        </select>
      </div>
      <div class="form-group col-md-4">
        <label for="novo_relatorio">Novo Relatório</label>
        <input type="text" class="form-control" id="novo_relatorio" name="novo_relatorio" maxlength="100" />
      </div>
      <div class="form-group col-md-4">
        <label for=""> </label>
        <div class="custom-control custom-switch">
          <input type="checkbox" class="custom-control-input" id="salvarrelatorio">
          <label class="custom-control-label" for="salvarrelatorio">Salvar Relatório?</label>
        </div>
      </div>
    </div>
    <div class="form-row">
      <div class="form-group col-md-4">
        <div class="form-check form-check-inline">
          <input class="form-check-input" type="checkbox" id="dipendentes" value="dipendentes">
          <label class="form-check-label" for="dipendentes">DI's Pendentes</label>
        </div>
      </div>
      <div class="form-group col-md-4">
        <div class="form-check form-check-inline">
          <input class="form-check-input" type="checkbox" id="registradas" value="registradas">
          <label class="form-check-label" for="registradas">DI's Registradas</label>
        </div>
      </div>
      <div class="form-group col-md-4">
        <div class="form-check form-check-inline">
          <input class="form-check-input" type="checkbox" id="entregues" value="entregues">
          <label class="form-check-label" for="entregues">DI's Entregues</label>
        </div>
    </div>    
    <div class="form-row">
      <div class="form-group col-md-5">
        <label class="control-label" for="Lista1">Disponíveis</label>
        <select multiple class="custom-select" id="Lista1">
          <option value="idt_embarque">IDENTIFICACAO</option>
          <option value="invoice">NR INVOICE</option>
          <option value="nr_doc_carga_mast">NR MASTER</option>
          <option value="nr_doc_carga">NR HOUSE</option>
          <option value="dt_di">DATA D.I.</option>
          <option value="nr_di">NR D.I.</option>
          <option value="qtd_adicoes">NR ADICOES</option>
          <option value="historico">HISTORICO</option>
        </select>
      </div>
      <div class="form-group col-md-2">
        <label class="control-label" for="btnAdd"> </label>
        <button id="btnAdd" type="button" class="btn btn-outline-success" style="width:25px;height:25px;margin:55px 0 0 25px">
          <svg style="margin:-10px 0 0 -6px" width="15" height="15" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="angle-double-right" class="svg-inline--fa fa-angle-double-right fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34zm192-34l-136-136c-9.4-9.4-24.6-9.4-33.9 0l-22.6 22.6c-9.4 9.4-9.4 24.6 0 33.9l96.4 96.4-96.4 96.4c-9.4 9.4-9.4 24.6 0 33.9l22.6 22.6c9.4 9.4 24.6 9.4 33.9 0l136-136c9.4-9.2 9.4-24.4 0-33.8z"></path></svg>
        </button>
      </div>
<script>

    function mostra(lista){
        var x = lista.options[lista.options.selectedIndex];
        var nome = x.text;
        if(lista.value != "0"){
            $("#Lista2").prop("hidden", true);
            $.ajax({
                type: 'POST',
                url: 'relatorios.php',
                cache: false,
                data: { 'tabela': nome },
                success: function(retorno){
                    alert(retorno);
                }
            });
        }else{
            $("#Lista2").prop("hidden", false);
        }
    }

</script>
      <div class="form-group col-md-5">
        <label class="control-label" for="Lista2">Itens Rel.</label>
        <select multiple class="form-control" id="Lista2" name="Lista2[]">
          <option hidden selected value="cd_processo"></option>
          <option hidden selected value="dt_recebimento_doc"></option>
          <option value="idt_embarque">IDENTIFICACAO</option>
          <option value="invoice">NR INVOICE</option>
        </select>
      </div>
<?php
    //var_dump($_POST);
    @$tabela = $_POST['tabela'];
    $opcoes = "";
    $cabeca = "";
    $campo = array("/idt_embarque/i","/invoice/i","/nr_doc_carga_mast/i","/nr_doc_carga/i","/dt_di/i","/nr_di/i","/qtd_adicoes/i","/historico/i");
    $titulo = array("IDENTIFICACAO","NR INVOICE","NR MASTER","NR HOUSE","DATA D.I.","NR D.I.","NR ADICOES","HISTORICO");

    $arg = array("select"=>"*","tabela"=>"TAB_RELATORIOS","where"=>"where login='{$_SESSION['login']}' and nome='{$tabela}'");
    $obj_rel = $obj_pdo->getConsultaDI($arg);
    if(!empty($obj_rel)){
        $opcoes = explode("|",$obj_rel[0]->OPCOES);
        $tl_rel = count($opcoes)-1;
        print '<div class="form-group col-md-5">';
        print '<label class="control-label" for="Lista2">Itens Rel.</label>';
        print '<select multiple class="form-control" id="Lista2" name="Lista2[]">';
        for($i=0; $tl_rel > $i; $i++){ //inicio do for
            $cabeca = preg_replace($campo, $titulo, $opcoes[$i]);
            if($opcoes[$i] === "cd_processo"){
                print '<option hidden selected value="cd_processo"></option>';
            }elseif($opcoes[$i] === "dt_recebimento_doc"){
                print '<option hidden selected value="dt_recebimento_doc"></option>';
            }else{
                print '<option value="'.$opcoes[$i].'">'.$cabeca.'</option>';
            }
        }// fim do for
        print '</select>';
        print '</div>';
    }
?>
    </div>
    <div class="form-row">
      <div class="form-group col-md-5">

      </div>
      <div class="form-group col-md-2">

      </div>
      <div class="form-group col-md-5">
        <button type="button" class="btn btn-sm" id="btnUp">
          <svg width="20px" height="20px" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="arrow-alt-circle-up" class="svg-inline--fa fa-arrow-alt-circle-up fa-w-16 text-success" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M8 256C8 119 119 8 256 8s248 111 248 248-111 248-248 248S8 393 8 256zm292 116V256h70.9c10.7 0 16.1-13 8.5-20.5L264.5 121.2c-4.7-4.7-12.2-4.7-16.9 0l-115 114.3c-7.6 7.6-2.2 20.5 8.5 20.5H212v116c0 6.6 5.4 12 12 12h64c6.6 0 12-5.4 12-12z"></path></svg>
        </button>
        <button type="button" class="btn btn-sm" id="btnDown">
          <svg width="20px" height="20px" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="arrow-alt-circle-down" class="svg-inline--fa fa-arrow-alt-circle-down fa-w-16 text-success" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z"></path></svg>
        </button>
        <button type="button" class="btn btn-sm" id="btnRemove">
          <svg width="20px" height="20px" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="times-circle" class="svg-inline--fa fa-times-circle fa-w-16 text-success" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm121.6 313.1c4.7 4.7 4.7 12.3 0 17L338 377.6c-4.7 4.7-12.3 4.7-17 0L256 312l-65.1 65.6c-4.7 4.7-12.3 4.7-17 0L134.4 338c-4.7-4.7-4.7-12.3 0-17l65.6-65-65.6-65.1c-4.7-4.7-4.7-12.3 0-17l39.6-39.6c4.7-4.7 12.3-4.7 17 0l65 65.7 65.1-65.6c4.7-4.7 12.3-4.7 17 0l39.6 39.6c4.7 4.7 4.7 12.3 0 17L312 256l65.6 65.1z"></path></svg>
        </button>
      </div>
    </div>
    <div class="form-row">
      <div class="form-group col-md-7">
        <div class="btn-group" role="group">
          <button id="consultar" type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            VISUALIZAR
          </button>
          <div class="dropdown-menu" aria-labelledby="consultar">
            <button type="submit" class="dropdown-item" name="tela">
              <svg width="15" height="15" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="tv" class="svg-inline--fa fa-tv fa-w-20" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path fill="currentColor" d="M592 0H48A48 48 0 0 0 0 48v320a48 48 0 0 0 48 48h240v32H112a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16H352v-32h240a48 48 0 0 0 48-48V48a48 48 0 0 0-48-48zm-16 352H64V64h512z"></path></svg>
              Tela</button>           
            <button type="submit" class="dropdown-item" name="excel">
              <svg width="15" height="15" aria-hidden="true" focusable="false" data-prefix="far" data-icon="file-excel" class="svg-inline--fa fa-file-excel fa-w-12" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M369.9 97.9L286 14C277 5 264.8-.1 252.1-.1H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V131.9c0-12.7-5.1-25-14.1-34zM332.1 128H256V51.9l76.1 76.1zM48 464V48h160v104c0 13.3 10.7 24 24 24h104v288H48zm212-240h-28.8c-4.4 0-8.4 2.4-10.5 6.3-18 33.1-22.2 42.4-28.6 57.7-13.9-29.1-6.9-17.3-28.6-57.7-2.1-3.9-6.2-6.3-10.6-6.3H124c-9.3 0-15 10-10.4 18l46.3 78-46.3 78c-4.7 8 1.1 18 10.4 18h28.9c4.4 0 8.4-2.4 10.5-6.3 21.7-40 23-45 28.6-57.7 14.9 30.2 5.9 15.9 28.6 57.7 2.1 3.9 6.2 6.3 10.6 6.3H260c9.3 0 15-10 10.4-18L224 320c.7-1.1 30.3-50.5 46.3-78 4.7-8-1.1-18-10.3-18z"></path></svg>
              Excel</button>
            <button type="submit" class="dropdown-item" name="pdf">
              <svg width="15" height="15" aria-hidden="true" focusable="false" data-prefix="far" data-icon="file-pdf" class="svg-inline--fa fa-file-pdf fa-w-12" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M369.9 97.9L286 14C277 5 264.8-.1 252.1-.1H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V131.9c0-12.7-5.1-25-14.1-34zM332.1 128H256V51.9l76.1 76.1zM48 464V48h160v104c0 13.3 10.7 24 24 24h104v288H48zm250.2-143.7c-12.2-12-47-8.7-64.4-6.5-17.2-10.5-28.7-25-36.8-46.3 3.9-16.1 10.1-40.6 5.4-56-4.2-26.2-37.8-23.6-42.6-5.9-4.4 16.1-.4 38.5 7 67.1-10 23.9-24.9 56-35.4 74.4-20 10.3-47 26.2-51 46.2-3.3 15.8 26 55.2 76.1-31.2 22.4-7.4 46.8-16.5 68.4-20.1 18.9 10.2 41 17 55.8 17 25.5 0 28-28.2 17.5-38.7zm-198.1 77.8c5.1-13.7 24.5-29.5 30.4-35-19 30.3-30.4 35.7-30.4 35zm81.6-190.6c7.4 0 6.7 32.1 1.8 40.8-4.4-13.9-4.3-40.8-1.8-40.8zm-24.4 136.6c9.7-16.9 18-37 24.7-54.7 8.3 15.1 18.9 27.2 30.1 35.5-20.8 4.3-38.9 13.1-54.8 19.2zm131.6-5s-5 6-37.3-7.8c35.1-2.6 40.9 5.4 37.3 7.8z"></path></svg>
              PDF</button>
          </div>
        </div>
<!--        <input type="submit" class="btn btn-outline-success" id="consultar" name="consultar" value="CONSULTAR" /> -->
      </div>
    </div>
  </div>
</form>
<script>
    $('#btnAdd').click(function (e) {
        $('select').moveToList('#Lista1', '#Lista2');
        e.preventDefault();
    });
    $('#btnRemove').click(function (e) {
        $('select').removeSelected('#Lista2');
        e.preventDefault();
    });
    $('#btnUp').click(function (e) {
        $('select').moveUpDown('#Lista2', true, false);
        e.preventDefault();
    });
    $('#btnDown').click(function (e) {
        $('select').moveUpDown('#Lista2', false, true);
        e.preventDefault();
    }); 
</script>
</body>
</html>
  • 1

    You display what you choose to display. If you call a page that responds to the whole HTML and put it to display the whole HTML, it will display the whole HTML. Detail your code better. This code snippet (javascript) that you put up does not match the result that you detailed. " display all HTML in the console" but what ta in the code is to give a whole code Alert.

  • @Fabricio I will post all the code, maybe it is clearer. But in short what I want is, use the text displayed in the first selectA to create a second selectB.

1 answer

1


From what I understand you’re leaving both codes on the same page.

When you are doing the POST via ajax you are receiving the entire code. When you just want to receive the code that contains your select.

You can even leave everything in a . php only, but have to validate that return. Example:

File reports.php

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') && (!empty($_POST['tabela'])) {
        //var_dump($_POST);
        @$tabela = $_POST['tabela'];
        $opcoes = "";
        $cabeca = "";
        $campo = array("/idt_embarque/i","/invoice/i","/nr_doc_carga_mast/i","/nr_doc_carga/i","/dt_di/i","/nr_di/i","/qtd_adicoes/i","/historico/i");
        $titulo = array("IDENTIFICACAO","NR INVOICE","NR MASTER","NR HOUSE","DATA D.I.","NR D.I.","NR ADICOES","HISTORICO");

        $arg = array("select"=>"*","tabela"=>"TAB_RELATORIOS","where"=>"where login='{$_SESSION['login']}' and nome='{$tabela}'");
        $obj_rel = $obj_pdo->getConsultaDI($arg);
        if(!empty($obj_rel)){
            $opcoes = explode("|",$obj_rel[0]->OPCOES);
            $tl_rel = count($opcoes)-1;
            print '<div class="form-group col-md-5">';
            print '<label class="control-label" for="Lista2">Itens Rel.</label>';
            print '<select multiple class="form-control" id="Lista2" name="Lista2[]">';
            for($i=0; $tl_rel > $i; $i++){ //inicio do for
                $cabeca = preg_replace($campo, $titulo, $opcoes[$i]);
                if($opcoes[$i] === "cd_processo"){
                    print '<option hidden selected value="cd_processo"></option>';
                }elseif($opcoes[$i] === "dt_recebimento_doc"){
                    print '<option hidden selected value="dt_recebimento_doc"></option>';
                }else{
                    print '<option value="'.$opcoes[$i].'">'.$cabeca.'</option>';
                }
            }// fim do for
            print '</select>';
            print '</div>';
        }
        // Sair para não enviar mais nada.
        exit;
    }
?>
<!doctype html>
<html lang="pt-br">
<head>
<title>Relatório de Follow Up Honda</title>
//restante do seu código

Normally I leave it in another .php. file.Example: reports2.php

No matter how you do that part. You need to change your AJAX to when you receive the success of the call exchange the contents of the div with the returned code. Example:

function mostra(lista){
    var x = lista.options[lista.options.selectedIndex];
    var nome = x.text;
    if(lista.value != "0"){
        $("#Lista2").prop("hidden", true);
        $.ajax({
            type: 'POST',
            url: 'relatorios.php',
            cache: false,
            data: { 'tabela': nome },
            success: function(retorno){
                //alert(retorno);
                $("#Lista2").html(retorno);
            }
        });
    }else{
        $("#Lista2").prop("hidden", false);
    }
}

Tip: Instead of leaving Istener with onclick in select, use onchange.

Dica2: Do not leave the name as a query variable. Use the value you already populate in the value of your option. So you are not restricted in the format of the name you want to display to the user. In addition to being much more logical and simple programming. You can use for example the primary key of your table in value, which will make your query to the bank more performative. Instead of searching for a giant string without an index, query for an indexed integer.

  • how can I do to receive the value of my select and put the same in a variable PHP? I want to do it on the same page, without having to do a refresh.

Browser other questions tagged

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