LocalStorage + PHP

0

I'm capturing the data from a LocalStorage, but when I put the information in a PHP variable and search the server, the query does not execute correctly.

<?php 
session_start();

try{
 require('conexao.php');
 $igreja="<script>document.write(localStorage.igreja);</script>";// aqui pega o valor localstorage igreja

$sql = "SELECT descricao, data, hora FROM 'reuniao' WHERE id_igreja = '".$igreja."' order by 2,3 LIMIT 1";
echo $sql;
$stmt = $conexao->prepare($sql);
$stmt->execute();
}
catch(PDOException $e) {
 echo 'ERRO: ' . $e->getMessage() ;
}
?>
<!doctype html>
<html>
<head>
    <title>Igreja, que Horas?</title>
    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta charset="utf-8">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Compiled and minified CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css" rel="stylesheet" >
    <link href="icons/material.css" rel="stylesheet">        
    <link href="estilo/materialize.min.css" rel="stylesheet">
    <link href="estilo/estilos.css" rel="stylesheet">
</head>
<body>
    <header>
        <nav>
            <img src="imagens/logo.png" width="50" class="brand-logo">

            <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a>

            <ul class="right hide-on-med-and-down">
                <li><a href="index.php">Reunião Geral/Comunhão</a></li>
                <li><a href="celula.php">Grupo Caseiro/Célula</a></li>
                <li><a href="configuracao.php">Configurações</a></li>
                <li><a href="mailto:[email protected]">Contato</a></li>
            </ul>
        </nav>

        <ul class="sidenav" id="mobile-demo">
            <li><a href="index.php">Reunião Geral/Comunhão</a></li>
            <li><a href="celula.php">Grupo Caseiro/Célula</a></li>
            <li><a href="configuracao.php">Configurações</a></li>
            <li><a href="mailto:[email protected]">Contato</a></li>
        </ul>
    </header>
</body>

<h6 class="titulo container">Sua próxima reunião será em..
</h6>
  <div class="collection">
     <?php
            while($consulta = $stmt->fetch()){
     ?>
        <a class="collection-item waves-effect"><?php echo date('d/m/Y', strtotime($consulta["data"]))." ".date('H:i', strtotime($consulta["hora"]))." ".$consulta["descricao"];?></a>
    <?php
        }
      try{
        require('conexao.php');
        $sql = "SELECT data, hora, descricao from reuniao where id_igreja = 1 and data != (select data from 
         reuniao where id_igreja = 1 
         order by 1 LIMIT 1)";
        $stmt = $conexao->prepare($sql);
        $stmt->execute();
      }
      catch(PDOException $e) {
        echo 'ERRO: ' . $e->getMessage() ;
     }
    ?>  
  </div>
<h6 class="titulo container">Reuniões futuras..</h6>
  <div class="collection">
        <?php
            while($consulta = $stmt->fetch()){
        ?>
            <a class="collection-item waves-effect"><?php echo date('d/m/Y', strtotime($consulta["data"]))." ".date('H:i',  strtotime($consulta["hora"]))." ".$consulta["descricao"];?></a>
        <?php
            }
        ?>
  </div>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><!--CompiledandminifiedJavaScript--><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="js/funcoes.js"></script>
<script>
 var igreja = localStorage.getItem('igreja');
 $.POST('index.php', {'igreja':igreja}, function(data){
 alert('Login Successful.  Redirect to a different page or something here.');
 }
 </script>
 </html>
    
asked by anonymous 31.07.2018 / 04:43

1 answer

1

2nd your ajax is executed, you are assigning a value to the church variable and sending via post, you need to capture that same variable post before using it in your query.

Your code is structured, so it gets a bit complicated to maintain, I rewrote the part that does the ajax request and uses the localstorage to return the data I suggest that instead of using localstorage use the browser cookie, php has $ _COOKIE, is much simpler to caputrar, without doing this XGH via post.

Below the solution with localstorage and cookie.

Localstorage.

I needed to sort things out to be more organized.

index.php

  ...
    <h6 class="titulo container">Reuniões futuras..</h6>
    <div class="collection" id="result">
    </div>
    ...
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script><script>varvalue=localStorage.getItem('igreja');jQuery.post("action.php", {igreja: value}, function(data)
    {
        $('#result').html(data);

    }).fail(function()
    {
        console.log("Algo está errado.");
    });


</script>
</html>

action.php

    try {
    require 'conexao.php';
    $value = isset($_POST['igreja']) ? $_POST['igreja'] : "";
    if (!$value) {
        throw new Exception('Parametro não informado');
    }

    $sql = "SELECT descricao, data, hora FROM 'reuniao' WHERE id_igreja = '" . $value . "' order by 2,3 LIMIT 1";
    $stmt = $conexao->prepare($sql);
    $stmt->execute();

    while ($consulta = $stmt->fetch()) {

        $html = "<a class='collection-item waves-effect'>";
        $html .= date('d/m/Y', strtotime($consulta["data"])) ;
        $html .= date('H:i',  strtotime($consulta["hora"])) ;
        $html .= $consulta["descricao"] ;
        $html .= "</a>" ;

    }

    echo  $html;
} catch (PDOException $e) {
    echo 'ERRO: ' . $e->getMessage();
}

The code is tested, but I did not care so much about beauty.

Using cookie

<?php
session_start();

try{
    require('conexao.php');
    $igreja= $_COOKIE['igreja'];
//    $igreja="<script>document.write(localStorage.igreja);</script>";// aqui pega o valor localstorage igreja

    $sql = "SELECT descricao, data, hora FROM 'reuniao' WHERE id_igreja = '".$igreja."' order by 2,3 LIMIT 1";
    echo $sql;
    $stmt = $conexao->prepare($sql);
    $stmt->execute();
}
catch(PDOException $e) {
    echo 'ERRO: ' . $e->getMessage() ;
}
?>
<!doctype html>
<html>
<head>
    <title>Igreja, que Horas?</title>
    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta charset="utf-8">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Compiled and minified CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css" rel="stylesheet" >
    <link href="icons/material.css" rel="stylesheet">
    <link href="estilo/materialize.min.css" rel="stylesheet">
    <link href="estilo/estilos.css" rel="stylesheet">
</head>
<body>
<header>
    <nav>
        <img src="imagens/logo.png" width="50" class="brand-logo">

        <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a>

        <ul class="right hide-on-med-and-down">
            <li><a href="index.php">Reunião Geral/Comunhão</a></li>
            <li><a href="celula.php">Grupo Caseiro/Célula</a></li>
            <li><a href="configuracao.php">Configurações</a></li>
            <li><a href="mailto:[email protected]">Contato</a></li>
        </ul>
    </nav>

    <ul class="sidenav" id="mobile-demo">
        <li><a href="index.php">Reunião Geral/Comunhão</a></li>
        <li><a href="celula.php">Grupo Caseiro/Célula</a></li>
        <li><a href="configuracao.php">Configurações</a></li>
        <li><a href="mailto:[email protected]">Contato</a></li>
    </ul>
</header>
</body>

<h6 class="titulo container">Sua próxima reunião será em..
</h6>
<div class="collection">
    <?php
    while($consulta = $stmt->fetch()){
        ?>
        <a class="collection-item waves-effect"><?php echo date('d/m/Y', strtotime($consulta["data"]))." ".date('H:i', strtotime($consulta["hora"]))." ".$consulta["descricao"];?></a>
        <?php
    }
    try{
        require('conexao.php');
        $sql = "SELECT data, hora, descricao from reuniao where id_igreja = 1 and data != (select data from 
         reuniao where id_igreja = 1 
         order by 1 LIMIT 1)";
        $stmt = $conexao->prepare($sql);
        $stmt->execute();
    }
    catch(PDOException $e) {
        echo 'ERRO: ' . $e->getMessage() ;
    }
    ?>
</div>
<h6 class="titulo container">Reuniões futuras..</h6>
<div class="collection">
    <?php
    while($consulta = $stmt->fetch()){
        ?>
        <a class="collection-item waves-effect"><?php echo date('d/m/Y', strtotime($consulta["data"]))." ".date('H:i',  strtotime($consulta["hora"]))." ".$consulta["descricao"];?></a>
        <?php
    }
    ?>
</div>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><!--CompiledandminifiedJavaScript--><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="js/funcoes.js"></script>

<!-- biblioteca para usar cookies facilmente https://github.com/js-cookie/js-cookie-->
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

<script>
    Cookies.set('igreja', '1'); //em algum momento você vai setar esse valor antes dessa pagina

    var igreja = localStorage.getItem('igreja');
    $.POST('index.php', {'igreja':igreja}, function(data){
        alert('Login Successful.  Redirect to a different page or something here.');
    }
</script>
</html>
    
31.07.2018 / 06:16