Localstorage + PHP

Asked

Viewed 6,560 times

0

I am capturing the data from a Localstorage, but when I put the information in a PHP variable and search on the server, the query does not perform 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>

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

    You’re just assigning the $church variable a string with script and everything. You should take $_POST, like this: $igreja = $_POST['igreja'];. No way to get localStorage directly in PHP.

1 answer

2


1º in the $.POST('index.php', ... missing close parentese, this generates a javascript syntax error, and your ajax will not run.

2º your ajax runs, you are assigning a value to variable church and sending via post, need to capture that same variable post before using in your query.

Your code is structured, so it gets a little complicated to maintain, I rewrote the part that makes 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, it is much simpler to caputrar, without doing this XGH via post.

Below the solution with localstorage and cookie.

Localstorage.

I had 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>
    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>

php action.

    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 didn’t 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>

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

    Perfect friend! I forgot to use Cookies, much easier for this type of situation, thank you!

Browser other questions tagged

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