如何使用AJAX,PHP和MySQL实时发送通知?

如何使用AJAX,PHP和MySQL实时发送通知?

问题描述:

I would like to make real-time notification on my website. I have the notification bar:

<div class="alert alert-info alert-with-icon" data-notify="container">
  <button type="button" aria-hidden="true" class="close">
     <i class="nc-icon nc-simple-remove"></i>
  </button>
  <span data-notify="icon" class="nc-icon nc-bell-55"></span>
  <span data-notify="message"><h6>TEXT HERE</h6></span>
</div>

I would like to place my text in the space provided above.

I created a JS function to call a PHP file that will read in the database the last message.

JS code in index.php :

function charger() {

      setTimeout( function(){
        $.ajax({
          url : "charger.php",
          type : GET,
          success : function(html){
            $("h6").prepend(html);
          }
        });

        charger();

      },5000);
    }

    charger();

PHP File in charger.php :

<?php

  $servername = "localhost";
  $username = "scanner";
  $password = "valentin";
  $dbname = "Scanner3D";

  try {
    $bdd = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  catch(PDOException $e)
  {
  }

  // Recuperation des notifications du Scanner
  $requete = $bdd->query('SELECT message FROM notifications ORDER BY id DESC');

  $messages = null;

  while($donnees = $requete->fetch()){
    $messages = $donnees['message'];
  }

  echo $messages;

?>

But I can not display the text I read in my database in my notification location.

GET is not defined as you should have it surrounded by quotes since it's the name of the HTTP method you'll use, not a variable in your code.

$.ajax({
    url: "charger.php",
    type: "GET",
    success: function(html){
        $("h6").prepend(html);
    }
});

BTW, you should throw an eye on setInterval.

<script type="text/javascript">
 $.ajax({
  url: "charger.php",
  type: "GET",
  success: function(html){
     $("h6").prepend(html);
  }
});

refer Ajax notification system with jquery, php and mysql