Guest User

Untitled

a guest
Aug 7th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. <p id="value">The value is 1 now.</p>
  2. <button id="check">Check Value</button>
  3.  
  4. var button = document.getElementById('check');
  5. //Trigger button click.
  6. button.addEventListener('click', function(){
  7. //Check if EventSource is supported.
  8. if(typeof(EventSource)!="undefined")
  9. {
  10. //EventSource to 'index.php'
  11. var evtSource = new EventSource('index.php');
  12. //Trigger receiving a massage.
  13. evtSource.addEventListener("msg", function(e) {
  14. var obj = JSON.parse(e.data);
  15. //Check if the value is 2.
  16. if( obj == '2' ){
  17. //Change the paragraph.
  18. paragraph.innerHTML = 'The value is 2 now.';
  19. //Close EventSource.
  20. evtSource.close();
  21. }
  22. }, false);
  23. }
  24. });
  25.  
  26. header('Cache-Control: no-cache');
  27. header("Content-Type: text/event-streamnn");
  28.  
  29. //Connect to the DB.
  30. $servername = "localhost";
  31. $username = "root";
  32. $password = "";
  33. $dbname = "value";
  34. try {
  35. $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  36. // set the PDO error mode to exception
  37. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  38. }catch(PDOException $e){
  39. echo "Error: " . $e->getMessage();
  40. }
  41.  
  42. //Fetch the value.
  43. $val = $conn->prepare('SELECT v FROM val');
  44. $val->execute();
  45. $val = $val->fetchAll();
  46. $val = $val[0]['v'];
  47.  
  48. //Check the value
  49. if ($val == '2') {
  50. echo "event: msgn";
  51. echo 'data: "2"';
  52. echo "nn";
  53.  
  54. }
  55.  
  56. ob_flush();
  57. flush();
Add Comment
Please, Sign In to add comment