Page freezes for seconds when ajax post working - ajax

When i use jquery's $.post ajax function, page freezes for 2-3 seconds and then data received. Freezing time can change depends on the data received.
How can i prevent this ?
EDIT:
COde i am using, it actually receives very large data
$.post("../ajax_updates.php", { time: last_update }, function(data) {
if (data) {
if (data != "") {
$("#news_feed").prepend($(data).fadeIn('slow'));
}
}
});

If you load big amount of data through JavaScript this is normal, the problem is caused because your request is synchronous which will make your browser to wait this request to end before do anything else.
You need to make your request asynchronous
P.S. Use $.get instead of $.post to get information from the server, in some cases - specially if you code work under Windows IIS you will get an error about that.
P.S-1. And it make sense $.get is for getting data from the server and $.post is for sending data.
Try this:
$.ajaxSetup({
async: true
});
$.get("../ajax_updates.php", { time: last_update }, function(data) {
if (data && data != "") {
$("#news_feed").prepend($(data).fadeIn('slow'));
}
});

When you send the ajax request make sure that async is set to true. If it is set to false, the browser will freeze untill a response is received.
http://api.jquery.com/jQuery.ajax/

Related

browser performance after some ajax calls

I use jquery to make an ajax request every 15 seconds to update a <DIV> Element with information. That works generally fine but after some minutes, when the ajax request runs a few times, I got browser performance issues. I only need to run the page in firefox, but here is the problem most of all.
This is the way I call the function every 15 sec.:
setInterval(syncdiv, 15000);
This is my ajax request:
function syncdiv() {
$.ajax({
url: 'code_get_msg_sync.php?',
cache: false, // The problem exist with cache true even with false
success: function(data) {
$('#msgdiv').html(data);
}
});
}
Try using
e.preventDefault();
before you submit or click to send a ajax request ..Just a try
Also there are few links for reference
Link 1
Link 2
Link 3

How to avoid discontinuity in periodical HTTP request by jQuery?

I am new to jQuery and want to use it to retrieve data from a server every 3 seconds. The web server sends data every 3 seconds in JSON format. The JSON data contains a numerical array field { "samples" : [10,15,-7,19,34,...] }. I wrote the following jQuery ajax request to retrieve data from the server every 3 seconds:
function getData() {
$.ajax({
url : 'http://example.com',
type: 'GET',
success : function(data) {
myData = data.samples;
setTimeout(getData, 3000);
},
dataType : 'json'
});
return myData;
}
However, due to timing jitter, the data sent from the server may not get updated precisely at every 3 seconds. So how should I write the jQuery ajax request to avoid the possible data discontinuity? That is, I want the returned myData contains all fresh new data array elements from each getData() call and does not contain duplicated or missing data samples due to possible timing jitter.
Send the last timestamp that the data was updated on the server along with the other JSON array. Then, when it is time to request data again using your jQuery call, check the timestamp against what you already have. This will give you a way to know if it is the same data, or if it has been refreshed.
I think you may need pass around more info. Include another field in your AJAX called "lastUpdate" with a timestamp. Your javascript can save the last timestamp it got and provide it to the server. The server responds only with samples after that timestamp (so you don't miss any) and won't respond with anything if its still up to date (so you don't duplicate).
There's little point returning myData. (a) the variable is not declared within the function, and (b) the data arrives asynchronously from the server.
As it stands, getData() is guaranteed (at best) to return the data obtained at the previous iteration.
To work with the freshly obtained data, you need to do whatever is necessary with myData within the success function or in a done() callback, as follows :
function getData() {
$.ajax({
url: 'http://example.com',
type: 'GET',
dataType : 'json'
}).done(function(data) {
var myData = data.samples;
//Do whatever is necessary with myData here.
//Call extenal function as necessary to do the job.
setTimeout(getData, 3000);
});
}
Write your code in such a way that takes advantage of the asynchronous nature of ajax. For example,
var interval;
function handleData(data) {
// I handle the data returned from the ajax request.
console.log(data);
}
function getData() {
// I send the ajax request.
$.ajax({
url: 'http://example.com',
success: handleData,
error: function(){
// on error, stop making requests to help with debugging.
console.log(arguments);
clearInterval(interval);
}
});
}
interval = setInterval(getData,3000);
This will result that in most cases, the responses will come in order. You can make that true in all cases if you get rid of the interval and instead call get data 3 seconds after the previous success.
function getData() {
// I send the ajax request.
$.ajax({
url: 'http://example.com',
success: handleData,
error: function(){
// on error, stop making requests to help with debugging.
console.log(arguments);
}
});
}
function handleData(data) {
// I handle the data returned from the ajax request.
console.log(data);
setTimeout(getData,3000);
}
getData();
Side note: the "timing jitter" isn't a jitter at all, it's simply a logic error. The data is always one set behind due to Ajax being Asynchronous.

First ajax call on Phonegap + Zepto returns undefined even after device ready

I'm doing a jsonp call in my mobile app at startup to connect to my server. I'm using Phonegap 2.1 and Zepto 1.0-rc1. At the bottom of my html page, I do the init stuff on DOM ready.
<script type="text/javascript">
if (!$) {$ = Zepto};
$(init);
document.addEventListener('deviceready', Perksea.deviceReady);
</script>
...
function init() {
var router = new Backbone.Router();
...
}
function deviceReady() {
isConnected();
isConnected();
}
function isConnected() {
$.ajaxJSONP({
url: 'http://localhost/isconnected',
success: function(response) {
console.log('response is ' + response);
}
});
}
The first JSONP call will print "response is undefined" but the second JSONP call works. I've even tried putting the JSONP call in a setTimeout(isConnected, 5000) with the same result. Have already checked that the url is correct etc.
Has anyone seen something like this?
Thanks
Steve
since you are getting into the "success" callback function on the first call (where response is undefined), are you sure that your server is properly responding to the first call? Sounds like it is returning a 200 response, but with no data for that first call.
You can try adding an 'error' callback to see if that provides anything useful as well
$.ajaxJSONP({
url: 'http://localhost/isconnected',
success: function(response) {
console.log('response is ' + response);
}
error: function(response) {
console.log('error is ' + response);
}
});
Finally, because AJAX is Asynchronous, your 2 calls to isConnected() are going to fire one immediately after the other, not waiting for the first to respond. I'm curious what it looks like on the server side (see above).

Browers entering "busy" state on Ajax request

I am currently implementing a sort of HTTP Push using Long Polling for browsers that don't support multipart ajax responses.
I have to admit that while the server side is working fine, i am relativly new to front end javascript development, and thus may have made some obvious mistakes
The problem is as follows LongPolling works perfectly on IE 6,7,8 and Firefox ( even though Firefox uses multipart i tested it with long polling too ) but Safari and Chrome enter
the browsers "busy" state during the ajax requests. ( they show the windows wait cursor, and Safari also shows its "Loading" indicator in the title bar )
This is of course not desireable..
Here is my code to do the long poll based on Jquery 1.4.1:
function MepSubscribeToQueueLongPoll(name, callback) {
var queueUrl = MepGetQueueUrl(name, "LongPoll");
MepLongPollStep(queueUrl, callback);
};
function MepLongPollStep(url, callback) {
$.ajax({
url: url,
async: true,
cache: false,
success: function (data,status,request) {
callback(request.responseText);
MepLongPollStep(url, callback);
}
});
};
Note that i am bypassing the data parsing functionality of Jquery by passing the request.responseText directly to the callback because Jquery does not seem to support multipart ajax respones and i wanted to be consistent across communication paths.
Since no better answer has stepped forward, I wonder if a simple timeout would solve the problem. Sorry to give a "guess" instead of a "I know this to be true answer", but this might actually fix it.:
function MepLongPollStep(url, callback) {
$.ajax({
url: url,
async: true,
cache: false,
success: function (data,status,request) {
callback(request.responseText);
window.setTimeout( function(){
MepLongPollStep(url, callback);
},10);
}
});
};

ajax synchronous call with timeout

New to ajax, so asking a very basic question.
-- Is there no way to make a Synchronous ajax call (async:false) with timeout set on it.?
http://www.ajaxtoolbox.com/request/
Timeout works perfect with Asynchronous call though in my application,
but for one particular scenario, I need a Synchronous call (the javascript should actually wait untill it hears back from the server), and this also works fine. But I need to handle a scenario where the sever could take long and a ajax timeout may be called.
Is there any other piece of standard documentation for ajax I could refer to?
Thanks
Basically, during a synchronous ajax request, the browser is blocked and no javascript can be executed while the browser is blocked. Because of this, jQuery can't abort the ajax request after a set timeout because jQuery is javascript and javascript can't be executed while the browser is blocked. This is the primary flaw in synchronous ajax.
Anytime you might want a synchronous request, you should instead use an asynchronous one with what should happen afterwards in the callback, as shown below;
$.ajax({
url : 'webservices.php',
timeout: 200,
dataType : 'json',
data : {
'cmd' : 'ping',
},
success : function(data, textStatus) {
$.ajax({
url : 'webservices.php',
async: false,
dataType : 'json',
data : {
'cmd' : 'feedback',
'data' : data,
'userinfo' : window.dsuser
},
success : function(data, textStatus) {
// success!
Status("Thanks for the feedback, "
+ window.dsuser.user + "!");
}
});
},
error : function(jqhdr, textStatus,
errorThrown) {
Status("There was trouble sending your feedback. Please try again later");
}
});
I don't believe it's possible to set a timeout on a synchronous call. When you set "async:false", I believe the browser actually locks up while waiting for the response. You should only use a synchronous request if you absolutely need to (because of the browser locking up).

Resources