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.
Related
I have a website that basically makes API calls and displays the data in a table; the API is on a different server from the website.
If the API server is down what is the best way to alert the user client-side (JavaScript) that the server is unavailable?
Could/Should I put the alert in the API call error handling (See code for example)? What is the best practice for this type of situation.
function apiCall(query, product){
var p = product;
var urlr='https://myFakeAPIUrl/api/'+query+'/'+ product;
$.ajax({
contentType: 'application/json',
crossDomain: true,
url: urlr,
type: "GET",
success: function (result){
alert("Yay, the API server is up.");
},
error: function(error){
console.log(error);
alert("Sorry, the server is down.");
}
});
}
var productData = apiCall("Produce", "112233");
I would ask myself what a user would like to see in this situation.
What I always do is putting a timeout on the Ajax request, whenever that timeout of e.g. 9999ms runs out, the user should get notified (with a toast, a heading, etc..) that something went wrong and that they should try it again later.
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) {
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.
This question already has answers here:
Check if Internet Connection Exists with jQuery? [duplicate]
(9 answers)
Closed 8 years ago.
Assuming there is no internet connection, of course. Like a jQuery method?
I would try to make HEAD requests (no content downloaded) to a few servers you know are online. They will automatically fail if there is no network (no need to set a timeout).
$.ajax({
type: "HEAD",
url: 'http://www.google.com',
error: function() {
alert('world is gone !');
}
});
DEMONSTRATION (unplug your network to test)
If you are dealing with ajax requests, you can catch timeout error - see error(jqXHR, textStatus, errorThrown) in $.ajax reference.
Sort of, yes. Before the actual submission, you can have an ajax call try to connect to a simple lightweight service on your site just to check if it is reachable.
If the call fails, you can assume there's no connection.
With help of failed XHR requests you can determine the connection.
Retry few times , if the request doesnot go through, alert and fail gracefully.
I can use this function which I got from http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/
$.networkDetection = function(url,interval){
var url = url;
var interval = interval;
online = false;
this.StartPolling = function(){
this.StopPolling();
this.timer = setInterval(poll, interval);
};
this.StopPolling = function(){
clearInterval(this.timer);
};
this.setPollInterval= function(i) {
interval = i;
};
this.getOnlineStatus = function(){
return online;
};
function poll() {
$.ajax({
type: "POST",
url: url,
dataType: "text",
error: function(){
online = false;
$(document).trigger('status.networkDetection',[false]);
},
success: function(){
online = true;
$(document).trigger('status.networkDetection',[true]);
}
});
};
};
One way to go about it is to send your form using AJAX. Then you'll have a handler that will tell you that it wasn't able to connect to the server and you can save the data and inform the user that the server is not available. It doesn't really matter whether the problem is your internet connection or the server may be down.
if (navigator.onLine) {
alert('online');
} else {
alert('offline');
}
I have an ajax application, which has code something like this:
$.ajax({
type: "GET",
url: "data.txt",
beforeSend:function(){
},
success:function(response){
just update responsed data;
}
});
this call is made every second and it just updates the latest data from 'data.txt' which is being updated on server using cron job. Now since it's only function is to update latest data each second so I'll be more interested in the latest ajax call ; so how can I terminate old ajax call that has crossed 4 seconds but yet not completed so that I can reduce the server traffic. And any suggestion if using 'data.html' or 'data.php' instead of 'data.txt' would increase the application performance ? And which web server can perform better than Apache for ajax driven application ? I need these help urgently ; Please do help.
You could keep track of when your last successful update time was.
function NowMS() {return parseInt(new Date().getTime())}
dataLastUpdateT = -Infinity;
$.ajax({
type: "GET",
url: "data.txt",
success: function(response){
if (NowMS() > dataLastUpdateT) {
use(response);
dataLastUpdateT = NowMS();
}
}
}
I don't know how you have it setup at the moment but perhaps it would be better to run your next AJAX call after the latest one completed (or returned an error). So it would be something like:
(function updateData() {
$.ajax({
type: 'GET',
url: 'data.txt',
beforeSend: function() {
// Do stuff
},
success: function(response) {
// Handle response
updateData();
}
});
})();
I don't know if there is any performance changes in changing the file type.
Edit: If you do need to just kill the request, you can do so using the technique explained here.
You could try this:
function getData(){
$.ajax({
type: "GET",
url: "data.txt",
timeout:4000,
beforeSend:function(){
},
success:function(response){
},
error:function(){
},
complete:function() {
setTimeout(function(){getData();},1000);
}
});
}
getData();
this way the ajax request timeouts after 4 seconds and retries each second (regardless of success or timeout)
Also have a look at nginx for example, it is fast and uses less memory than apache to handle client connections