Ajax long polling after page refresh - javascript

I have an AJAX long polling request below:
$.ajax({
type: "GET",
url: "events_controller.php",
dataType: "json",
success: function (data) {
eventsTimer = setTimeout(function(){eventsTimerHandler()}, 1000);
}
});
On the server, if some event happens then it will return what has happened and the request above will display a notification.
A problem I am having is if I do something on the browser to trigger an event that will happen in say 10 seconds in the future and then immediately go to a different page, it will create a new long polling request but the previous one is still active and no notification will be sent to the user.
I hope I'm making sense.

Related

Ajax call on setInterval timer not working

I have what should be a very simple little process. I have an interval timer which, when it expires, makes an ajax call to the server. With the json that comes back, it parses it out and updates the DOM. The setInterval is set to one second. The server then does a very simple SELECT on the database. It executes a query which takes milliseconds to execute, if that.
On our test server, it's working fine. But when it's deployed to our customer it is most of the time NOT actually hitting the database. We can see it in query analyser. There should be a continuous flow of queries, but they are sporadic at best, often 40 or more seconds between hits.
Here's the code:
setTimeout(function run() {
// When the timer elapses, get the data from the server
GetData(0);
setTimeout(run, _refreshRate);
}, 1000);
function GetData(isFirstLoad) {
//console.log("Attempting to obtain the data...");
jQuery.ajax({
url: "something.ashx",
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
//console.log("Got the data.");
ParseJson(resultData);
// show the last refresh date and time
$('#refreshTime').html(GetDateTime());
},
error : function(xhr, textStatus, errorThrown) {
if (textStatus == 'timeout') {
//console.log("Timeout occured while getting data from the server. Trying again.");
// If a timeout happens, DON'T STOP. Just keep going forever.
$.ajax(this);
return;
}
},
timeout: 0,
});
}
Everything within ParseJson(resultData); works fine. And with this line...
$('#refreshTime').html(GetDateTime());
...the time gets refreshed every one second like clockwork, even though the database never gets hit.
And I can put a breakpoint in the debug tools inside the error and it never gets hit.
If we hit refresh, it works or a few seconds (we can see queries hitting the database) but then it slows way down again.
The frustrating part is that it works flawlessly on our test server. But there is clearly something I'm overlooking.
EDIT:
Ok, this is really weird. When I have debugger open, it works. As soon as I close the debugger, it stops working. I don't even have to have the network tab running and capturing events. Just the debugger window open makes it work.
This is IE, which is what the client is using so it's our only option.
Found the answer here:
jQuery ajax only works in IE when the IE debugger is open
Turns out iE, and only IE, will cache ajax responses. You have to tell it not to. Adding cache: false did the trick.
function GetData(isFirstLoad) {
//console.log("Attempting to obtain the data...");
jQuery.ajax({
url: "something.ashx",
type: "GET",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function(resultData) {

Ajax call slows down and crashes browser

I have a chat application that uses ajax to get messages from database as below:
setInterval(function () {
$.ajax({
type: "GET",
url: "chat.php",
dataType: "json",
success: function (response) {
$(".chat").html(response);
if (response !== lastResponse) {
var audio = new Audio('audio/vibes.mp3')
audio.play()
}
lastResponse = response
}
});
}, 5000);
I am sure the reason is because it calls every 5 seconds. Please is there a fix for this using ajax such that it doesn't slow down the browser?
Note: I heard of web-sockets recently and planning to improve the chat app with web-sockets.
I just need a quick fix for now. Thanks in advance.
Try Server Sent Events as the code in it only executes when there is some change in the server unlike your case in which it is executing after every 5 seconds.

In Backbone how do I trigger a method every time I execute an Ajax call?

So, every time I have an AJAX call in my Backbone app, I want to hit a method which essentially goes off the the server and checks if I'm authenticated using a JWT token. This token has an expiry time, so let's say that the expiry time is 1 minute for sake of argument. If I stay on that page and upload a file after 30 seconds, all is well. If I upload a file 2 minutes later, it should check if I'm authenticated, see that I'm not, and boot me back to the login page.
Now, of course I could add this call to the method in every one of my AJAX calls like so (I wouldn't do it in an if like below, but this is just to illustrate my point...)
if (isAuthenticated === true) {
$.ajax({
url: '/dosomething',
type: 'POST',
data: data,
processData: false,
cache: false,
contentType: false
}).done(function () {
//do stuff here
}).fail(function (jqXHR, textStatus) {
console.log(jqXHR);
console.log(textStatus);
});
}
The problem is is that I have a lot of AJAX calls, so it feels like I'm wasting time by adding this method call to every AJAX call. I'm not too familiar with all of Backbone's ins and outs, so I just wondered if there was something I could do to bind my method to ALL AJAX calls?
Cheers!
Have you tried ajaxSend? https://api.jquery.com/ajaxSend/
$(document).ajaxSend(function(e, xhr) {
if (isAuthenticated === false){
xhr.abort();
}
});

window.onbeforeunload not always firing?

My application relies on being able to set a user Online/Offline state.
I have solved this by using the window.onbeforeunload to see when the user leaves a page.
The problem is that the below code does not always get executed and is therefore still saying that some people are online when they have left the page.
This is my current code:
window.onbeforeunload = function (event) {
$.ajax({
type: 'GET',
url: './changeStatus.php?cid=' + ccID + '&status=0',
contentType: "application/json",
dataType: 'json',
cache: false,
async: false,
success: function (data) {},
error: function (e) {
//console.log(e);
}
});
return;
};
Any ideas how i can force this to always get executed? (On all browsers)
The script is probably always executed when the page closes, but that doesn't mean that it always succeeds in calling the server.
If for example the user disconnects the internet connection before closing the page, the script can't send anything to the server. You simply can't rely on getting a call from the browser every time the page is closed.
You can keep track on the server when the user was last heard of, so that you can set the user as offline when he hasn't requested any pages for a while. Another alternative is to frequently send a request to the server as long as the user is on the page, and when the requests stop coming, the server knows that the user has gone away.

How can i stop ajax request (don't wait untill response come)?

If I use Ajax to send request and this request take long time ..... if I want to send anther request what should I do?
the current behaviour the second request (I did) waiting until the first request get with response.
NOTE :
i want to do this behaviour on whole application (any new request execute immediately not wait the old one to be finished firstly)
My application using (Ajax + PHP + jQuery + Symfony)
Assume that is the first request take long time:
$.ajax
({
type: "GET",
url: url1,
success: function (html)
{
// do some thing
}
});
In any time I want this request to execute and terminate the first one.
$.ajax
({
type: "POST",
url: url,
success: function (html)
{
// do some thing else
}
});
var xhrReq;
xhrReq = $.ajax(...);
// then if you want to stop the rqest and exit use :
xhrReq.abort();
It’s sort of a manual process, but you can add a global xhr object and test it on each request. If the readystate is "loading", abort it:
var xhr;
var loadUrl = function(url) {
if ( xhr && xhr.readyState > 0 && xhr.readyState < 4 ) {
// there is a request in the pipe, abort
xhr.abort();
}
xhr = $.get(url, function() {
console.log('success', this);
});
};
loadUrl('/ajax/');
The XMLHttpRequest object has an abort function. You can use setTimeout to abort a request that is taking too long.
EDIT: In the case you do not want to use a timer, and a new event occurs that should abort the prior request, then the event handler should do the following
if(!this.request) return; // request contains the XMLHttpRequest
this.request.onreadystatechange = function() {};
if(this.request.readyState != 4) {
this.request.abort();
}
Then after that you can create the new XMLHttpRequest object.
I have been working on this many ways and I feel I found a working solution. I had a caching process that was causing a page to hang until done (average 5 seconds). Yes this is better suited as a CRON job, but I needed to create caching process for the user without knowing the environment they are using for my CMS.
What I had done:
Create the call within a variable and then remove it by a hard delete. By deleting this it seems to be removing the wait. This "hack" seemed to pull the wait from 5 second average to a 325ms wait.
var ignore = $.ajax({
url:something/here.php,
type: "GET",
url: url1,
success: function(){}
});
delete ignore;
Defining the ajax request variable:
var xhr;
Making the ajax call:
xhr = $.ajax(...);
Aborting the ajax call:
xhr.abort();
Browser allows you to handle only limited amount of requests to same host at time (2 or 3 as I remember, depending on browser).
Workaround on requests count is to make fake domains - like img1.domain.com, img2.domain.com, etc. leading to the same host and randomly use them in requests. Then you can just make requests you need. Domains count should be chosen depending on requests quantity in order to keep in bounds - 2 requests per domain. Otherwise 3rd request will wait until one of active finishes.
It allows you to receive responses from all your requests.
For example, Google uses it to make images load faster.
EDIT:
Example: you have http://yourhost.com/ and alias http://alias.yourhost.com which points to the same place.
Then:
$.ajax
({
type: "GET",
url: 'http://yourhost.com/somescript.php',
success: function (html)
{
// do some thing
}
});
and then
$.ajax
({
type: "POST",
url: 'http://alias.yourhost.com/somescript2.php',
success: function (html)
{
// do some thing else
}
});

Categories

Resources