Polling Apache server not responding - php

The apache server I am using to develop my system will not respond to request while the scripts that control the polling of messages is being run. This only happends on a domain level meaning that I can send an http request to any other apps hosted localy and get a response. When I do eventually get a response from this its about a minute later.
Here is the Js
window.fetch_messages = function ()
{
var last_message = $("div.message:last").attr('data-ai_id');
var last_message_status = $("p.message_status:last").text();
var project_id = getParameterByName('project-id');
$.ajax({
url:'/project_messages',
type:'POST',
data:{ project_id:project_id, latest_message:last_message, status:last_message_status },
timeout:50000,
async: true,
success:new_messages, // This upon completion also resends the request
error:function(data){ console.log(data); setTimeout(fetch_messages(),50000); }
});
}; // When On the page that uses this I call this function to start polling
Here is the server side code
do
{
// Check for status change
$status_change = $this->mentor_model->query_status($this->project_id, $this->last_message_id, $this->last_message_status, $_SESSION['user']);
// Check for new messages
$messages = $this->mentor_model->query_messages($this->project_id, $this->last_message_id);
// If there is a status update or new message.
if($messages || $status_change)
break;
usleep(1000000);
}
while(empty($messages) && empty($status_change));
echo json_encode(array("messages"=>$messages, "status"=>$status_change));
exit;
While this action is being run The server takes a long time to handle any request weather it be a GET, POST or another AJax request. Iv also tried changing both code sets to no avail as long as its long polling, the server will take a long time to handle.
Do I have this wrong or is there some apache setting I'm suppose to change. Using xamp on windows 8.1 also tried wamp with no change

Thanks to steven for this. Ansewer taken straight from the source of php manual page
for session_write_close();
You can have interesting fun debugging anything with sleep() in it if
you have a session still active. For example, a page that makes an
ajax request, where the ajax request polls a server-side event (and
may not return immediately).
If the ajax function doesn't do session_write_close(), then your outer
page will appear to hang, and opening other pages in new tabs will
also stall.

Related

Dynamically get data from database using Ajax without a refresh interval

I have been working with jquery/ajax requests. I have successfully got a ajax request which will retrieve data from a database, the problem is, that i'm constantly serving window.setInterval() to refresh this function every x amount of seconds.
How would I change this to keep the ajax request alive, so it updates the html content without having to serve multiple requests to my ajax script.
My code follows:
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'Ajax.php'+SearchTerm, dataType: 'json', success: function(rows)
{
$('#NumberOfVotes').empty();
for (var i in rows)
{
var row = rows[i];
var QuestionID = row[0];
var Votes = row[1];
$('#NumberOfVotes')
.append(Votes);
}
}
});
});
}, 500);
A lot of this depends on how your server would be able to update it's content dynamically. That said, what you are looking for is websockets. Websockets are designed to replace the long-polling paradigm.
EDIT: Since you use mainly php for your server technology, look at Ratchet. I've heard good things about it http://socketo.me/
Here is an excellent article on using websockets with HTML
http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/
.NET has a great socket library in SignalR
http://signalr.net/
There is a myriad of php documentation on sockets out there
http://php.net/manual/en/book.sockets.php
look into using web sockets - you could send the client a message anytime they need to go an look for new data - that way your not making any unnecessary requests. Try checking out pubnub -service is cheap and could handle everything you need.
You could set xhr.multipart = true and modify server code. see Multipart Responses Example Code. Alternative way is to use websockets as mentioned
You need something server side that keeps the request alive until it has something to return. This is usually called "Comet", "Long-polling" or "Push".
The principle is :
You send a request client-side via AJAX
Your server receives the request, and doesn't return a response yet. It sleeps/waits until it has something to return
A new entry in your database ! Your server now has something to return : it returns some JSON data for the waiting request
Your receive the response server side, display what you have to display, and go back to step 1 sending another request.
Now, the implementation server side will depend on the language/framework you are using.
Edit :
Some examples using PHP :
Comet and PHP
Simple Comet Implementation Using PHP and jQuery

jQuery ajax call never finishes (success and error callbacks are not fired)

I've an ajax request to the server and I only need to know when it finishes to redirect the user to a second page. It is working most of the times but if the server takes too long to answer (e.g. 10 min) then it can happen that no callback function is called and the request keeps waiting.
My code is as follows:
$.ajax({
type: 'post',
url: 'request.php',
success: function(data) {
alert("Success: "+data);
window.location.replace("success.php");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Ajax error: "+xhr.status+" - "+thrownError);
window.location.replace("error.php");
}
});
As you can see, I've tried to check if there is any error but as far as I have arrived, the ajax request behaves as if it had not finished (no alert or redirection is fired). However, the PHP code in the server runs without errors until the end.
I have no idea where to search for the error because I was thinking about a timeout problem both in the browser or in the server but it seems not to be the cause. And as the same code is working in short waiting times I cannot imagine other possible reasons.
Thank you!
I would bet on a timeout on your web server which invalidates the connection, this might mean that no answer is sent back.
In that case, the ajax timeout option might be good for you.
Having said that, if I were you, I would do this differently: since you're already using ajax, why not ping the server every x seconds and check if the process has finished and it's time to redirect, instead of keeping the connection open? This way you don't have timeout issues, and you don't hold the connection captive over a session which doesn't send any data and only waits for a server side process to finish. More scalable and robust, and more appropriate for http connections.

Avoiding 'Script not responding' with Reverse AJAX / Comet?

I have a worker thread that sends out a request to the server for data using an XMLHttpRequest. That request points to a php file that basically checks the current integrity of the information that the client has and if the client needs the new information then it is sent. Otherwise the server checks information until the client needs a response. After the server responds the whole process is repeated.
The problem arises when the browser realizes the script isn't responding and gives the user the option to stop the script. As you can see, this isn't the intended result. So what's the best way to continue using the comet-like structure without confusing the browser?
EDIT: I realized why the script is hanging, I repeated the whole worker thread instead of repeating the somewhere deeper inside the thread. So I guess my question now where to start the process again, after it finishes.
<?php
//Client sends their current id
if(isset($_GET['id']))
$id = $_GET["id"];
//if id doesnt match servers id send them a new one
//other wise do not respond
$server_id = file_get_contents("ids.txt");
while($server_id == $id){
$server_id = file_get_contents("ids.txt");
sleep(1);
}
echo $server_id;
?>
Javascript:
self.addEventListener('message', function(e) {
var data = e.data;
switch (data.cmd) {
case 'start':
getInfo(data.id);
self.postMessage('ID :: ' + response);
break;
default:
self.postMessage('Unknown command');
};
}, false);
var response = null;
var request = new XMLHttpRequest();
function getInfo(inputID){
var url = "serverResponse.php?id=" + inputID;
request.open("GET", url, false);
request.onreadystatechange = updateState;
request.send(null);
}
function updateState(){
if(request.readyState == 4){
if(request.status == 200){
response = request.responseText;//getInfo(data.id);
}
}
}
html:
<html>
<script type="text/javascript">
function sayHI() {
var id = "666";
worker.postMessage({'cmd': 'start', 'id' : id});
}
var worker = new Worker('AjaxWorker.js');
worker.addEventListener('message', function(e){
document.getElementById('result').textContent = e.data;
//Some data has been received so go ahead and make another call to the server
//This is where the script hangs because the worker waits for a response
sayHI();
}, false);
</script>
<body>
<button type="button" name="submit" id="submit" onclick="sayHI()">Submit</button> </br></br>
<output id="result" name="result">Result</output>
</body>
</html>
Your line:
request.open("GET", url, false);
has the async argument of open() set to false, meaning that the JavaScript execution flow completely stops on that Ajax call until it completes. Your webpage is completely frozen until that synchronous call resolves, and since you're using long polling, that won't happen for a very long time. Thus, your browser's interpreter sends you a warning that script execution is taking a suspiciously long time. (This warning is completely legitimate, too -- you can't do anything at all on your page until the synchronous call resolves.)
You need to use request.open("GET", url, true);. Just move anything that needs to happen after the Ajax call and place it inside the onreadystatechange callback. When the server finally responds, the updateState function will fire. Anything that should happen in response to a "comet push" (i.e. the resolution of a long-poll query by a response from the server) needs to go in that callback.
Asynchronous Ajax will allow the script execution to continue and won't cause your JS interpreter to hang. Instead of waiting for the long-polling query to resolve, the script flow will move right past it, and at some later time the onreadystatechange callbacks will be called with new information from the server.
EDIT:
The JavaScript interpreter only has one thread. If that thread is utilized nonstop for a long period of time, the browser will suspect something has gone wrong and issue a warning. Your synchronous Ajax call grabs the single JS thread and doesn't let go until the server finally replies. As I said earlier, during that long time, nothing else can happen on the page. The interpreter is stuck on that call.
With synchronous Ajax, your flow looks like this:
send synchronous request
wait
and wait
and wait
(meanwhile, nothing else can get done)
and wait...
....
finally a response comes!
use the response to update the page
Consider this superior asynchronous Ajax alternative:
send ansyc request
[the interpreter sleeps and the browser is happy]
a response comes!
the request's readystatechange event fires now
the onreadystatechange handler uses the response to update the page
In the second example, the interpreter gets to take a break instead of waiting for the Ajax request to resolve. Your onreadystatechange handler function is fired whenever the Ajax call comes back from the server. If your call is synchronous, the interpreter does nothing until the call resolves. If your call is asynchronous, the interpreter is free to do anything it likes -- including rest and not cause a browser warning -- until the call resolves and it executes your onreadystatechange handler.
You don't say what technique you are using to implement reverse AJAX (HTTP polling? HTTP streaming? WebSockets? Something else?) If you're using polling, the server is supposed to respond promptly, even if it's "nothing new here".
If you're holding a connection open, this can cause a problem; HTTP limits a browser to two simultaneous connections to a server. In that case, the browser and any other scripts only have one connection to work with; this can cause the browser to think things are blocked. A standard approach to this is to create a separate host name for comet interactions.
If you use a WebWorker, the browser won't complain about it being blocked. (However, the issue of connection count could still cause problems.)

jQuery AJAX Wait

I have constructed a PHP file which scrapes a web page (using cURL) to obtain some data, and outputs it to the screen in JSON format.
The target website involves some redirects which temporarily outputs data to my PHP file. Once the redirects have completed successfully, the JSON is presented as expected. The problem that I am encountering is that when I try to access the JSON using jQuery's $.ajax() method, it sometimes returns the incorrect data, because it isn't waiting for the redirects to complete.
My question is if it's possible to tell the AJAX request to wait a certain number of seconds before returning the data, thus allowing time for the redirects in the PHP script to execute successfully?
Please note that there is no cleaner solution for the page scrape, the redirects are essential and have to be outputted to the screen for the scraping to complete.
There's always timeout in the settings.
jQuery docs:
timeout Number
Set a timeout (in milliseconds) for the request. This will
override any global timeout set with $.ajaxSetup().
The timeout period starts at the point the $.ajax call is made;
if several other requests are in progress and the browser
has no connections available, it is possible for a request
to time out before it can be sent. In jQuery 1.4.x and below,
the XMLHttpRequest object will be in an invalid state if
the request times out; accessing any object members may
throw an exception. In Firefox 3.0+ only, script and JSONP
requests cannot be cancelled by a timeout; the script will
run even if it arrives after the timeout period.
You should use promise() in jQuery.
You could always store the result of your ajax call and then wait for the redirects to finsih, i.e.:
$.ajax({
success: function(e)
{
var wait = setTimeout(function(){ doSomethingWithData(e.data); }, 5000); //5 sec
}
})
Alternatively, you could set up an Interval to check if something happened (redirect finished) every x amount of ms. I'm assuming your redirects are letting you know they completed?
http://examples.hmp.is.it/ajaxProgressUpdater/
$i=0;
while (true)
{
if (self::$driver->executeScript("return $.active == 0")) {
break;
}
if($i == 20) {
break;
}
$i++;`enter code here`
echo $i;
usleep(10000);
}

jquery php long polling request issue

I'm making a chat which is based on long polling (something like this )with PHP and jQuery. once whole page is downloaded in browser, a function makes a long polling request to the back-end with some timeout limit, when data comes from back-end it again makes the long-polling request and if any error, it will again make new long-polling request.
Problem : analyzing the traces by firebug, I've noticed that some times the long polling request is running 3 or 4 times, however it should not. there should only one long-polling request running per page.
however the code works perfectly. but long-polling request duplication is the issue.
function listen_for_message(){
// this functions is makes the long-polling request
$.ajax({
url: "listen.php",
timeout:5000,
success: function(data) {
$('#display').html(data);
listen_for_message();
}
error: function() {
setTimeOut("listen_for_message()",2000); // if error then call the function after 2 sec
}
});
return;
}
Try to terminate requests manualy:
var connection;
function longpoll() {
if(connection != undefined) {
connection.abort();
}
connection = $.ajax({
...
complete: function() {
longpool();
}
});
}
It may also be a Firefox/firebug issue (showing aborted connections as running), test it in Chrome.
UPDATE:
"In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period."
http://api.jquery.com/jQuery.ajax/

Categories