Long Polling using jQuery and PHP
Asked Answered
F

1

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));
    }   
?>
Fanestil answered 5/8, 2011 at 11:30 Comment(5)
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.Fanestil
What do you mean it's not working?Bronchitis
You mean you don't want another request if it's not even.Bronchitis
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.Fanestil
@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); }Sampan
S
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

Sampan answered 5/8, 2011 at 11:41 Comment(3)
That's exactly the same as my code just with a longer sleep? What does that do?Fanestil
@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?Sampan
@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 newSampan

© 2022 - 2024 — McMap. All rights reserved.