0

I use this code to have the same file for both html page and dynamic ajax response (using jQuery):

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    echo "AJAX reponse";
    exit;
}

?><!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Leash</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
    $(function() {
       $.get('', function(data) { alert(data); });
    });
    </script>
</head>
<body>
</body>
</html>

is it possible to do the same using Server Side Evens and EventSource?

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • Maybe you wanna try out WebSocket and some EventDriven backend like eg NodeJS? think it would be a better fit – Endless Dec 03 '16 at 16:41
  • @Endless I'm trying to run this on shared hosting where I don't have access to Node only php and CGI scripts and all ports are closed by firewall. – jcubic Dec 03 '16 at 16:47

1 Answers1

0

Looking at the headers in developer tools there is Accept: text/event-stream so you can check for presence of the header using:

if (isset($_SERVER['HTTP_ACCEPT']) && preg_match("%text/event-stream%", $_SERVER['HTTP_ACCEPT'])) {

// server side events code
}?><!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
...
</html><?php } ?>
jcubic
  • 61,973
  • 54
  • 229
  • 402