Pass parameter through AJAX

Asked

Viewed 201 times

2

I am making a page where the user click the button will display some database information, only it is passing only a part, I do not have much experience with javascript, my code is

<?php
  session_start();
  if((!isset ($_SESSION['logado']) == true)){
    unset($_SESSION['logado']);
    header('location:index.php');
  }     
  require_once "conn.php";
  require_once 'func.php';
  header('Content-Type: text/html; charset=UTF-8');
  $id = $_SESSION['id'];
  $nome = $_SESSION['nome'];
  $pv = $_SESSION['pv'];
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>.:: Painel ::.</title>
  <!-- Bootstrap core CSS -->
  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="css/estilo.css" rel="stylesheet">
  <!-- Bootstrap JS -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</head>
<body>
  <!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark static-top" style="background-color: #005da0;">
    <div class="container">
      <a class="navbar-brand" href="site.php"><img src="css/Asset-17.png"></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            <a class="nav-link" href="site.php">Home
              <span class="sr-only">(current)</span>
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="deslogar.php">Sair</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>
  <div class="container centraliza_tudo">
    <div class="filtro"> 
      <form method="POST" class="form-inline">
        <div class="form-group mx-sm-3 mb-2">
          <label class="col-sm-2 col-form-label col-form-label-sm">Inicial:</label>
          <input type="date" class="form-control" name="inicial">
        </div>
        <div class="form-group mx-sm-3 mb-2">
          <label class="col-sm-2 col-form-label col-form-label-sm">Final:</label>
          <input type="date" class="form-control" name="final">
        </div>
        <button type="submit" class="btn btn-primary mb-2">Filtrar</button>
      </form>
    </div>
    <div class="lista-data">
      <?php 
      if (isset($_POST['inicial'])) {
      ?>
      <table class="table table-striped table-bordered ">
        <thead>
          <tr style="background-color: #005da0 !important;color: white !important;">
            <th scope="col">Data</th>
            <th scope="col">Exibir</th>
          </tr>
        </thead>
        <tbody>
        <?php
          $inicial = $_POST['inicial'];
          $final = $_POST['final'];
          $sql = "SELECT * FROM tb_cupom WHERE id_consultor = $id AND cadastro between '$inicial' and '$final'";
          $stm = $conexao->prepare($sql);
          $stm->execute();
          $lista = $stm->fetchAll();

          $data_inicial = new DateTime( implode( '-', array_reverse( explode( '/', $inicial ) ) ) );
          $data_final   = new DateTime( implode( '-', array_reverse( explode( '/', $final ) ) ) );

          while( $data_inicial <= $data_final ) {

          $data = $data_inicial->format('Y-m-d');
          $cp = "";
          for ($i=0; $i < count($lista); $i++) {
            $cupom = $lista[$i]['cupom'];
            $cadastro = $lista[$i]['cadastro'];
            if ($data == $cadastro) {
              $cp .= "$cupom;";
            }
          }
          if ($cp != "") {
            $data = converte_data_sem_ano($data);
              echo '<tr>
                      <td>'.$data.'</td>
                      <td><button id="'.$cp.'" type="button" class="exibir btn btn-primary btn-sm">Exibir</button></td>
                    </tr>';
            }
          $data_inicial->add( DateInterval::createFromDateString( '1 days' ) );

          }
        }
        ?>
        </tbody>
      </table>
    </div>
    <div class="exibe-lista"></div>
  </div>
  <script type="text/javascript">
    $(function(){
      $('button.exibir').click(function(){
        var id = $(this).attr('id');
        $.ajax({
          type: "POST",
          url: "exibe_cupom.php?cp="+id,
          dataType:"text",
          success: function(res){
            $(".exibe-lista").children(".table-striped").remove();
            $(".exibe-lista").append(res);
            console.log(res);
          }
        });
      })
    });
  </script>
</body>
</html>

Strange that when I inspect the page it shows the ID like this ->

<button id="teste;teste2" type="button" class="exibir btn btn-primary btn-sm">Exibir</button>

But when I look at the net it passes only the test, exibe_cupom.php?cp=teste How can I resolve this? I thank you in advance.

1 answer

3


You should not use the element ID attribute for this purpose.

The ID attribute should be used to manipulate the element via JS and/or CSS.

I recommend using data-attribute for custom data passing.

Another detail is that you are sending a POST request but sending a query string in the url instead of the data in the post body.

you could ride a vector like this:

$cp = array();
for ($i=0; $i < count($lista); $i++) {
    $cupom = $lista[$i]['cupom'];
    $cadastro = $lista[$i]['cadastro'];
    if ($data == $cadastro) {
        //$cp .= "$cupom;";
        $cp[] = $cupon;
    }
}

With this you will have a vector with the data you want to send in the request and put in the document with

<button id="meuId" data-cupons="<?php echo json_encode($cp);?>" type="button" class="exibir btn btn-primary btn-sm">Exibir</button>

Your script would look similar to:

  <script type="text/javascript">
    $(function(){
      $('button.exibir').click(function(){
        var id = JSON.parse($(this).attr('data-cupons')); // Ou
        var id = JSON.parse($(this).data('cupons'));
        $.ajax({
          type: "POST",
          url: "exibe_cupom.php",
          data: {'id':JSON.stringify(id)},
          dataType:"text",
          success: function(res){
            $(".exibe-lista").children(".table-striped").remove();
            $(".exibe-lista").append(res);
            console.log(res);
          }
        });
      })
    });
  </script>

Remember that in your exibe_couponom.php you will need to use decoding parameters in order to use:

$ids = json_decode($_POST['id']);

A remark:

This reference I passed is in case you need to send a vector to the server.

Some links to deepen the studies:

Data Attributes https://www.w3schools.com/tags/att_data-.asp

jQuery post format https://api.jquery.com/jQuery.post/

Reference to json’s Encode/Decode methods in PHP https://www.php.net/manual/en/ref.json.php

Tutorial on how to do something similar to what you need https://www.kvcodes.com/2015/10/passing-javascript-array-to-php-through-jquery-ajax/

Some more information about JSON https://www.w3schools.com/js/js_json.asp

  • I could not understand very well by example, I until today used ajax just as button and select, I am very lay in javascript, I was kind of looking for tutorials to do, it worked to erase data quiet, just as sending to another page with no return, I thought it would work for this situation, I would have as you give me an example of this method that you spoke?

  • @Faillen gave an improved answer, including some references to deepen the studies

  • @Jorgelima he was giving syntax error in this function -> JSON.parse(), I removed it and it worked fine, thank you very much

Browser other questions tagged

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