Compare the current date to the due date and fire an email if Expired!! - PHP Javascript

Asked

Viewed 31 times

-1

I need to do a Javascript function that if it is missing 1 month for the "validade_driver" to expire, the text of the HTML table is changed from "Valid" to "Expired", and an email is sent to the client stating that it has expired. I have a basic knowledge of PHP and managed to do a simple function that adds 1 month from the current data_and compares with the "validade_driver" to define if there is 1 month left to expire or not yet, follow the code and the link working to facilitate the tests:

Link working: https://extendsclass.com/php-bin/53711e5
Click on "RUN" to execute the code

I just have no idea how to turn this function into Javascript or how to fire an email to the client when the status is changed to "Expired" in the table. If anyone knows better and can help I’d be grateful.

<?php

$data_atual = '2021-02-14'; // Simula a data atual, se acrescentar uns dias vai Expirar na tabela
$validade_motorista = '14/03/2021'; // Data de validade do motorista, será salvo nesse formato no sistema

$data_atual_1mes = date('d/m/Y', strtotime("+1 month", strtotime($data_atual))); // Pega a "data_atual" e adiciona 1 mês

echo '<b>Data atual:</b> ' . $data_atual . '<br>';
echo '<b>Data atual + 1 mês: </b>' . $data_atual_1mes . '<br>';
echo '<b>Validade do Motorista:</b> ' . $validade_motorista . '<br><br>';

?>


<table style="text-align: center;" border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>Motorista</th>
      <th>Validade Motorista</th>
      <th>Status Motorista</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Jonas Felipe</td>
      <td><?php echo $validade_motorista; ?></td>
      <td>
      <?php
      if ($data_atual_1mes > $validade_motorista) {
        echo '<span style="color: red;">Expirado!</span>';
      } else {
        echo '<span style="color: lime;">Válido!</span>';
      }
      ?>
      </td>
    </tr>
  </tbody>
</table>

1 answer

0

To send emails use the function mail() php here. To send more elaborately there is the Phpmailer library available here

In both cases you will need to study how to use both.

As the form of triggering your thinking is on the table and should not, the action of sending email should happen whenever the page is executed, or you will need to assemble a script running from time to time evaluating the situation and sending emails.

It is very common to have routines in the system, this can be done through some kind of task scheduler, although it is the most correct I realize that is not what you are looking for at the moment.

1st Option

Place the email trigger on the page loading itself, using an email sending function:

if ($data_atual_1mes > $validade_motorista) {
  if(sendMail('[email protected]', 'Validade Expirada', 'Conteúdo do e-mail', null) {
    //e-mail enviado
  }
  else {
    //e-mail não enviado
  }
  echo '<span style="color: red;">Expirado!</span>';
}

2nd option via AJAX

This does not override the first option that can continue to be executed but further below it:

if($_POST['ajax']) {
  $response  = "";
  if ($data_atual_1mes > $validade_motorista) {
    if(sendMail('[email protected]', 'Validade Expirada', 'Conteúdo do e-mail', null) {
      //e-mail enviado
      $response = '<span style="color: red;">Expirado! Email OK</span>';
    }
    else {
      $response = '<span style="color: red;">Expirado! Email NOK</span>';
    }
    
  }
  else {
    $response = '<span style="color: lime;">Válido</span>';
  }
  //mata a execução disponibilizando a resposta
  die($response);
}

Javascript (jQuery Ajax):

var expiraMotorista = function () {
  $.ajax({
    url: 'arquivo.php', //arquivo a ser executado
    type: 'POST', //ou GET
    data: {ajax: true} //parametros a serem enviados no POST/GET
  })
  .done(function(response) {
    //concluído sem erro
    //aqui seria possível atualizar a tabela com o response, usando um id <span id='situacao'>
    $("#situacao").html(response);
    console.log("sucesso");
  })
  .fail(function() {
    //falhou
    console.log("erro");
  })
  .always(function() {
    //executa sempre que concluído
    console.log("expiraMotorista() executada");
  });
}
var interval = window.setInterval('expiraMotorista()', 10000);  //10 segundos
expiraMotorista();

Follows a simple function I use to send emails using Phpmailer:

function sendMail($dests = null, $assunto = null, $body = null, $anexos = null) {
  global $mail_error;
  
  if($dests && $assunto) {
    //adiciona as bibliotecas
    require 'PHPMailer6/src/PHPMailer.php';
    require 'PHPMailer6/src/Exception.php';
    require 'PHPMailer6/src/SMTP.php';

    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->SMTPDebug = SMTP::DEBUG_OFF;
    //enviar utilizando o gmail
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;

    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->SMTPAuth = true;

    //dados da conta, se for gmail precisa habilitar o acesso a conta
    $mail->Username = "[email protected]";
    $mail->Password = "senha";
    //e-mail e nome que aparecerão na caixa dod destinatario
    $mail->setFrom('[email protected]', 'Remetente');
    $mail->CharSet = 'UTF-8';

    //adicionando os destinarios, espera-se um array
    if(is_array($dests) && count($dests) > 0) {
      foreach($dests as $d) {
        $mail->addAddress(trim($d));
      }
      $dests = implode(",",$dests); //para reportar os e-mails no erro
    }
    else {
      if($dests) {
        $mail->addAddress(trim($dests));
      }
    }

    //adicionando os anexos, espera-se um array
    if(is_array($anexos)) {
      foreach ($anexos as $key => $anexo) {
        $mail->addStringAttachment($anexo['arquivo'], $anexo['nome_anexo'].'.pdf');
      }
    }
    else {
      if($anexos) {
        $mail->addAttachment(trim($anexos));
      }
    }

    //assunto do e-mail
    $mail->Subject = $assunto;
    //este e-mail pode conter conteúdo html
    $mail->isHTML(true);
    //corpo do e-mail
    $mail->Body = $body;

    //se enviado
    if ($mail->send()) {
      return true;
    }
    else {
      //setar o erro na variavel global e pegar após a execução da função
      $mail_error = "Houve erro no envio do e-mail para ($dests): {$mail->ErrorInfo}";
      return false;
    }
  }
  else {
    $mail_error "Destinatário ou assunto não informado";
    return false;
  }
}
  • Perfect, thank you very much for the answer. I have a question regarding your first recommendation, to put a function in the page load, would not be triggered e-mail every time the page was loaded? Or you would also need to create a function that checks which id’s have already been sent and which ones have not...

  • I haven’t talked about it myself, but it’s fair that idependente of the choice there should be a control of who has already had the shipment performed, it’s usually a daughter table of the driver, or a general control table of e-mails, when sending the email records it and also saves if there was success or error in sending if there is a record of sending email that has succeeded after.

Browser other questions tagged

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