Performance difference between synchronous and AJAX calls - ajax

I have a normal HTTP request (no Ajax) and I return a response from server side. This takes around 350ms. The same response when returned through an Ajax call takes only 50 ms.
I checked also the processing or the time taken to prepare the response on the server side. This time is the same for both the requests. (For example, in both cases MyServlet handles the request and returns the response. I gave sysout in the doPost method and the time spent inside the Servlet is the same).

I hope you are aware, that AJAX is asynchronous? Could it be that you are measuring the time the call returns (should return immediately) and not until an actual response is received (onSuccess event called)?

Related

Throttle HTTP Request based on Available Memory

I have a REST API that is expected to receive a large payload as request body. The API calls a blocking method that takes 2 seconds to process each request and then returns 200 OK. I wish to introduce throttling based on available memory such that the API returns 429 Too Many Request when the available memory falls below a threshold.
When the threshold condition is met, I wish to reject subsequent requests right away, even before loading the large request payloads in my application memory. This will also give me some protection against denial of service attacks.
In a Java EE, Tomcat environment, if I use a Filter to check available memory, I understand the complete request is already loaded in memory. Is it then better to add the check in ServletRequestListener.requestInitialized method so that I can reject the request even before the app receives it?
P.S. I use the below formula to calculate available memory based on this SO post:
long presumableFreeMemory =
Runtime.getRuntime().maxMemory()
- Runtime.getRuntime().totalMemory()
+ Runtime.getRuntime().freeMemory();

Calling Jquery ajax with set interval blocks the page?

I have been calling the jQuery ajax function on timely basis by using setInterval function.
so when the first response success handler is called and being executed, 2nd request success handler gets called on after the first response handler gets executed since JAVASCRIPT supports only single threaded...and so on(a queue is maintained to process the success handlers)?? is my understanding correct? so there is chance for page blocking ?
this is because of multiple ajax requests, most browsers handle the ajax request and remember it the next time an ajax request to the same url is called and handle it a second time
1st setInterval ajax to abc.html handle [0]
2nd setInterval ajax to abc.html handle [0], [1]
3rd setInterval ajax to abc.html handle [0], [1], [2]
it keeps building and adding to the confusion to change this I add an unique identifier to the user e.g
$.post("myurl.html?randid="+Math.random(), {my: data}).done(function(data){ /*do stuff here*/});
if this is a meant to be loaded for a long time and have a ton of ajax request to the same page instead of just a random number you might want to use a time stamp. for me and most cases the random number works, hope this is enough to get you started.

Why does onreadystatechange go before req.open on POST Ajax request

I understand from this site that in the case of a POST Ajax request, we need to place the request.onreadystatechange function call before the request.open command. In GET requests we typically place them in the opposite order. Why the difference?
What does "typically" mean? Where do you see documented that you are supposed to do that with GET requests? request.onreadystatechange should always come first. By defining it after the request is initiated you open yourself up to the possibility that the event is fired prior to your handler being established.

ExtJS 4 - How to check if all current ajax requests are completed and then perform an action?

I have a page which fires Ajax requests for validations at server side. I need to perform an action when all the ajax requests have finished loading or are completed.
For this, I am using Ext.Ajax.isLoading() in a recursive function in following way:
function chechValid(){
if(Ext.Ajax.isLoading()){
checkValid();
}else{
//Code for Action 1
}
}//EOF
checkValid();
//Code for Action 2
The problem is that when I do this, browsers give the following errors:
Mozill FF - too much recursions
IE - Stack overflow at line:18134
If this recursion is a heavy thing for the browsers, then how to perform a task when all the Ajax requests have finished loading?
Using delay is not what I want as, if delay is used then browser begins executing the other code (like 'Code for Action 2' as shared above) which is not what is expected.
The main aim is that the browser shouldn't execute anything unless all the Ajax requests are complete and once completed then it should perform a particular action.
Any suggestions/help on this one?
Thanks in Advance.
PS: Using ExtJs 4.0.7
(Updated)More Detail about the actual situation:-
Here is brief description of the situtaion being faced - There is a form, in which I need to perform server side validations on various fields. I am doing so by firing an ajax request on blur event. Depending upon the server response of validation Ajax fired on blur, fields are marked invalid and form submission is not allowed. (Avoiding 'change' event as that causes alot of overhead on server due to high number of Ajas requests and also leads to fluctuating effects on a field when response from various such Ajax requests are received).
Things are working fine except in one case - when user modifies the value of a field and instead of 'tab'bing out from the field she directly clicks at the save button. In such a case, though, the blur event gets fired but the processing of 'Save' doesn't wait for Ajax Validation response and submits the form. Thus, I somehow need to check if Ajax requests have finihed loading and the process the saving of form. requestComplete would unfortunately not serve the purpose here. And if try using the recursion, then of course, the browser is hung due to high usage of resources. Same case occurs if I try using a pause script work around ( as shared here - Javascript Sleep).
Any possible workaround for this one?
TIA
Your method will lead to infinite recursion.
A better way is to register a callback function in Ext.Ajax.requestcomplete, something like this (not tested):
Ext.Ajax.on('requestcomplete', function(conn, response, options) {
if (!Ext.Ajax.isLoading()) {
//your action...
}
}
};
Unless I am misunderstanding the issue couldn't you create a couple of globals. I know globals are bad, but in this case it will save you quite a bit of headache. One global would be "formReady" and initially set it to false, the other would be "ajaxActive" and set to false. You would also add an onSubmit method that would validate that "formReady" was true and if not alert the user that validation was occurring (or you could set a timeout for form submission again and have a second validation that checks to see if "ajaxActive" is true). When the AJAX call is made it would set the variable "ajaxActive" to true and once complete would set formReady to true. You could also potentially resubmit the form automatically if the response from the AJAX was that the form was good.
Ext.Ajax.request() returns a transaction object when you call it, which is unique and allows you to recognise and abort specific Ajax requests.
By just calling Ext.Ajax.isLoading() without a specified transaction object, it defaults to the last request, which is why you have to call it recursively at the moment.
If it were me, I'd create an array of these transaction objects as you fire them off, and pass each of those in as optional parameters to the Ext.Ajax.isLoading() function to check if a particular request has finished. If it has, you can remove that transaction object from the array, and only progress with the save when your array is empty.
This would get round your recursion problem, since you've always got a finite number of requests that you're waiting on.
if (Object.keys(Ext.Ajax.requests).length === 0) console.log("No active requests");

Prototype.js, AJAX form submission occasionally returns status 0, XHR stays in readyState 1

I've got an odd problem here with Prototype 1.7.0 and an AJAX form submission using form.request().
The response status is either 202 or 200 depending on whether the server expects to be polled again with the same form submission after a timeout. 200 indicates that the response contents are done and are to be displayed to the user (backend uses WebWork's execAndWait-interceptor to execute a long-running job).
The problem is that most of the time, everything works just fine. However, occasionally, the response comes back as status code 0 and XMLHTTPRequest readyState 1. Firebug indicates correct response codes are coming from the backend, and that the actual response contents are fine, it's just that Prototype's on200 and on202 handlers do not fire (on0 does).
It appears there are similar issues reported over the Internet, but there is no conclusive solution. Is this some well known problem?
A response code 0 from prototype means that it can't communicate with the server. You can remedy this by adding an "on0: function() {}" event handler in your request.
How you handle it is up to you...either alert the user that something went wrong, and redisplay their form, or silently try and re-submit your request to the backend in a loop. If you choose the second option, set a wait timeout and each time you can't talk to the server multiply it by some factor so you don't infinite loop their browser.
You might also want to look into queuing these requests on the client-side so you're only firing one at a time, in order.
Hope that helps.

Resources