Make alerts on a page with javascript

Asked

Viewed 58 times

-1

Hello! I have to take the date that is in the database and make an alert in javascript two days before that date.

How do I put this alert in a javascript box on the system?

  • What have you ever tried to do?

  • What language back-end are you using? Generally to do this you will need more than just Javascript.

  • @Pauloimon the language being used is PHP. My question is just how to make this team in javascript.

  • If you want to display the alert(), can compare the dates on PHP and then spend some flag to your code within the tag <script>. No need to use AJAX nor CRON JOBS.

  • That’s right there @Pauloimon. Only I want to kind of create a div and I want that alert to appear in the div box. Not in a javascript Alert box.

1 answer

3


In the PHP, you could have something more or less like this:

<?php
    // Instancia o objeto MySQLi e faz a conexão com a base de dados
    // (Altere os dados com as credenciais do seu servidor MySQL)
    $conexao = new mysqli('host', 'root', 'pswd', 'db');

    // Declara a flag p/ exibição de mensagens como desativada
    $alerta = FALSE;

    // Consulta de exemplo
    // (Altere a consulta conforme a sua tabela)
    $sql = "SELECT `data` FROM `tabela` WHERE `id` = 1 LIMIT 1";

    // Executa a consulta
    $consulta = $conexao->query($sql);

    // Gera o resultado da consulta
    $resultado = $consulta->fetch_array();

    // Pega a data atual e converte p/ padrão timestamp do Unix
    $hoje = strtotime(date('Y-m-d'));

    // Converte a data do banco p/ padrão timestamp do Unix
    $data = strtotime($resultado['data']);

    // Verifica se a data ainda não foi ultrapassada
    if ($hoje < $data)
    {
        // Calcula a diferença em segundos
        $diferenca = $data - $hoje;

        // Converte a diferença p/ dias
        $dias = (int) floor($diferenca / (60 * 60 * 24));

        // Verifica se a quantidade de dias atende sua condição
        if ($dias <= 2)
        {
            // Ativa a flag p/ exibir mensagem
            $alerta = TRUE;
        }
    }

Now in your code HTML, you can generate the message using a simple PHP:

<div>
    <?php if ($alerta) { ?>
    <p>Atenção! Mensagem de alerta!</p>
    <?php } ?>
</div>

Reference:

Calculating the difference in days between two dates - Blog Thiago Belem

  • Thanks! That’s the idea right there...

Browser other questions tagged

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