Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <p id="value">The value is 1 now.</p>
- <button id="check">Check Value</button>
- var button = document.getElementById('check');
- //Trigger button click.
- button.addEventListener('click', function(){
- //Check if EventSource is supported.
- if(typeof(EventSource)!="undefined")
- {
- //EventSource to 'index.php'
- var evtSource = new EventSource('index.php');
- //Trigger receiving a massage.
- evtSource.addEventListener("msg", function(e) {
- var obj = JSON.parse(e.data);
- //Check if the value is 2.
- if( obj == '2' ){
- //Change the paragraph.
- paragraph.innerHTML = 'The value is 2 now.';
- //Close EventSource.
- evtSource.close();
- }
- }, false);
- }
- });
- header('Cache-Control: no-cache');
- header("Content-Type: text/event-streamnn");
- //Connect to the DB.
- $servername = "localhost";
- $username = "root";
- $password = "";
- $dbname = "value";
- try {
- $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
- // set the PDO error mode to exception
- $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- }catch(PDOException $e){
- echo "Error: " . $e->getMessage();
- }
- //Fetch the value.
- $val = $conn->prepare('SELECT v FROM val');
- $val->execute();
- $val = $val->fetchAll();
- $val = $val[0]['v'];
- //Check the value
- if ($val == '2') {
- echo "event: msgn";
- echo 'data: "2"';
- echo "nn";
- }
- ob_flush();
- flush();
Add Comment
Please, Sign In to add comment