3

So, I've been trying to do Long-Polling using the jQuery Library and PHP. I'm doing this so I can make some sort of real-time notifications system in the future. The code I have now isn't really working.

index.php

<html>
<head>
    <title>Long Polling</title>
    <script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.min.js'></script>
    <script type='text/javascript'>
        $(document).ready(function() {
            getData();
        });

        function getData() {
            $.ajax({
                type: "POST",
                url: "ajax.php",
                async: true,
                timeout: 50000,
                data: "get=true",
                success: function(data) {
                    $("#info").append(data);

                    setTimeout("getData()", 1000);
                }
            });
        }
    </script>
</head>
<body>
    <div id='info'></div>
</body>
</html>

Ajax.php

<?php
    if(rand(1, 100) % 2) {
        echo 'even';
    } else {
        sleep(rand(1, 4));
    }   
?>
Joshwaa
  • 840
  • 1
  • 11
  • 22
  • The requests are being sent, but it's sending a new request even if the if returns false, im trying to make it only recieve data if the if statement returns true. – Joshwaa Aug 05 '11 at 11:39
  • What do you mean it's not working? – ace Aug 05 '11 at 11:39
  • You mean you don't want another request if it's not `even`. – ace Aug 05 '11 at 11:40
  • Yeah, if `if(rand(1, 100) % 2)` returns true I want the request to be held open waiting for it to return true upon the next try. – Joshwaa Aug 05 '11 at 11:41
  • @Joshwaa: sure it's sending new request, even if it returns nothing, you got these lines success: function(data) { $("#info").append(data); setTimeout("getData()", 1000); } – genesis Aug 05 '11 at 11:53

1 Answers1

0

Try to use this for ajax.php

<?php
    if(rand(1, 100) % 2) {
        echo 'even<br />';
    } else {
        sleep(rand(8, 12));
    }   
?>

watch this and sometimes you have to wait up to 12 seconds

if you let him to complete in one second it appears to be broken, but it's not

genesis
  • 50,477
  • 20
  • 96
  • 125
  • That's exactly the same as my code just with a longer sleep? What does that do? – Joshwaa Aug 05 '11 at 11:43
  • @Joshwaa: your problem is that in your case it appears "broken", because you did receive even a lot times. Or what is "broken", what is not working? – genesis Aug 05 '11 at 11:51
  • @Joshwaa: it is not. When you'll loop over those news for 50 seconds, it's ok. It will output and send new request Only 1. after 50 seconds 2. when there is new new – genesis Aug 05 '11 at 12:06