How to stop timed out ajax call using JQuery - javascript

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

Related

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.

Nested AJAX Functions - 500 Internal Error

I'm trying to run a script and then if there's success, I want to run another script. I'm doing this through jQuery and AJAX. I've tried both scripts individually and they both work by themselves (the AJAX functions). Here is the code:
$.ajax({
url: '/v/vspfiles/inventory-update/automation.asp',
success:function(data){
if(data=="True"){
$.ajax({
type: 'GET',
data:"filename=inventory.csv",
url: '/v/vspfiles/inventory-update/createxml.asp',
success:function(data){
alert('it worked');
}
});
}
}
});
I get a 500 internal error on the /v/vspfiles/inventory-update/createxml.asp?filename=inventory.csv when I run the code this way. I don't know why since the code works when I visit the page directly and when I run the AJAX by itself but when it's nested I get a 500 error.
Any idea why that would be happening? Thanks for your help!
There's nothing wrong with your code; nesting of ajax calls is allowed. Your server may be configured improperly. You can try to delay the second ajax call to see if that make any difference.
$.ajax({
url: '/v/vspfiles/inventory-update/automation.asp',
success:function(data){
if(data=="True"){
setTimeout( function() {
$.ajax({
type: 'GET',
data:"filename=inventory.csv",
url: '/v/vspfiles/inventory-update/createxml.asp',
success:function(data2){
alert('it worked');
}
});
},5000 );
}
}
});
5 seconds may be too long but it should prove to you that nesting ajax calls is quite proper and may point to what configuration changes may be required on the server. Give it a try. After all, that's what troubleshooting is all about.

Add cache to ajax json request

I have a basic ajax call to parse a json file. I need to make sure I am not hitting the feed every time someone visits the page. How would I go about adding some sort of cache so the feed only get's requested say every say 2 hours?
$(function () {
$.ajax({
type: "GET",
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
May be you can use cookie store your time and check every time to know 2 hours time gap then you can call your function get the latest feed.
By default, is should get cached. You can set the option explicitly as shown below.
$(function () {
$.ajax({
type: "GET",
cache: true,
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
You can also use the below statement for all ajax calls on the page.
$.ajaxSetup({cache: true});

Delay between repeated AJAX call to a web method

I have a ASP.Net web app with jquery implemented on the client side. within a while loop, the client side jquery script makes an asynchronous call to a web method in the server side code. The call returns the status of a long running server side task which jquery uses to update the user. The goal is to have jquery repeatedly call the server until the status is complete, once done it breaks out of the while loop and notifies the user thatthe task is complete.
My problem is that the below code runs in a while loop, but I want to make it delay or sleep between each call in order to prevent overwhelming the server with status requests. I tried calling setTimeout in the code below, but it only works with the initial ajax call, every subsequent call occurs back to back. Is there a way to efficiently delay each subsequent call to the server? Is this the most efficient way to achieve the kind of behavior I'm describing? Ideally I'd like a 2-5 second delay between each call.
I have the following code
Client Jquery:
var alertTimerId;
$('input[name=btnStatus]').click(function () {
var result = false;
//Loop while server reports task complete is true
while (!result) {
alertTimerId = setTimeout(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
if(msg.d != false)
result = msg.d;
},
error: function (xhr, ajaxOptions, thrownError) {
alert('AJAX failure');
}
});
}, 2000);
if (count > 0) {
count--;
}
}
});
Server Side ASP
[System.Web.Services.WebMethod]
public static bool GetStatus()
{
return result;
}
How about something like the following? The idea is that the Ajax call is encapsulated in a function, doAjax(), and then from within the Ajax success handler if the result is false you use setTimeout() to queue up another call to doAjax, otherwise you take whatever action you want to take for a true result. (You could optionally call doAjax() from the Ajax error handler too.)
$('input[name=btnStatus]').click(function () {
function doAjax() {
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
if (!msg.d)
setTimeout(doAjax, 2000);
else {
// Success! Notify user here
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('AJAX failure');
}
});
}
doAjax();
});
(Note: I've removed the if statement with count, since it seemed to have no relevance to the question. If your real code uses it just update it within the Ajax success handler too.)
Underscore.Js has a .throttle() helper function:
throttle_.throttle(function, wait)
Creates and returns a new, throttled version of the passed function, that, when invoked
repeatedly, will only actually call the original function at most once
per every wait milliseconds. Useful for rate-limiting events that
occur faster than you can keep up with.
var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

Jquery Ajax Problem

Hi all;
var v_name = null;
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
$.data(document.body, 'v_name', mydata);
}
});
v_name = $.data(document.body, 'OutputGrid');
alert(v_name);
first alert undefined before alert work why ?
In addition to the other answers, also keep in mind that by default .ajax GET requests are cached, so depending on your browser, it may look like all of your requests are returning the same response. Workarounds include (but are not limited to): using POST instead of GET, adding a random querystring to your url for each request, or adding 'cache: false' to either your ajax call or to the global ajaxSetup.
To make it work, you have to place the alert() in the success function:
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});
AJAX calls are asynchronous, and therefore JavaScript would evaluate alert(v_name); before the server responds to the AJAX call, and therefore before the success function is called.
Your AJAX applications must be designed in such a way to be driven by the AJAX response. Therefore anything you plan to do with mydata should be invoked from the success function. As a rule of the thumb, imagine that the server will take very long (such as 1 minute) to respond to the AJAX request. Your program logic should work around this concept of asynchrony.
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});

Categories

Resources