0

Estou capturando os dados de um LocalStorage, mas quando coloco a informação em uma variavel PHP e pesquiso no servidor, a query não executa corretamente.

<?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>

 <!-- Compiled and minified JavaScript -->
<script src="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>
1
  • 1
    Você está apenas atribuindo à variável $igreja uma string com script e tudo o mais. Deveria pegar com $_POST, assim: $igreja = $_POST['igreja'];. Não tem como pegar diretamente o localStorage no PHP.
    – Sam
    31/07/2018 às 3:45

1 Resposta 1

3

1º no trecho $.POST('index.php', ... esta faltando fechar o parentese, isso gera um erro de sintax do javascript, e seu ajax não vai ser executado.

2º seu ajax é executado, você está atribuindo um valor a variavel igreja e enviando via post, precisa capturar essa mesma variavel post antes de usar na sua query.

Seu código é estruturado, então fica um pouco complicado de dar manutenção, eu reescrevi a parte que faz a requisição ajax e utiliza o localstorage para retornar os dados sugiro que ao invés de usar localstorage utilize o cookie do browser, o php tem $_COOKIE, fica bem mais simples de caputrar, sem fazer esse XGH via post.

Abaixo a solução com localstorage e cookie.

Localstorage.

Precisei separar as coisas pra ficar mais organizado.

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>
    var value = 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();
}

o código está testado, mas n me preocupei tanto com beleza.

Usando 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>

<!-- Compiled and minified JavaScript -->
<script src="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>
1
  • 1
    Perfeito amigo! Esqueci de utilizar o Cookies, bem mais fácil para este tipo de situação, obrigado! 31/07/2018 às 5:06

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .