running jquery.ajax causes to slow down in navigating to other page - javascript

I have jquery.ajax that always requesting data to the server.My problem is that when I
click some navigation menu I can't navigate it is very too slow.I tried to comment the method inside the success,it works fine I can navigate very fast because there is no request running...Any Idea how to make this work to have request running at the same time and I can navigate to other page.?.
More input greatly appreciated.
Thank you in advance.
$(function(){
getUpdates();
});
function getUpdates(){
type: "GET",
dataType:'json',
url: "updates.php",
error: function () {
setTimeout(getUpdates, 5000);
},
success: function(data){
//do something with the data
...
...
...
getUpdates(); //call again the function
}
});
}

It's not a good idea to start a new request as soon as the previous request finishes. There is no (good) solution for your problem - the best idea is to restructure your code. Since you're constantly pooling the server for new information, you might want to look into Comet or Socket.IO to implement some sort of push mechanism from the server.
That said, for a simple speedup, the best thing you can do is add a timeout in the success function, the same way you did with the error function.

Related

Why is my async jQuery ajax call blocking?

I have read many similar questions to mine from long ago but have yet to find the answer to my problem, so apologies if it sounds so familiar.
I have a Laravel/PHP web app which loads in an excel file of transactions. These are processed as either success or failure. In development it takes about two seconds per transaction. A typical file has about 40 transactions. I am now wanting to use the Bootstrap progress bar to provide feedback to the user about how far along the processing is going.
I have a page with a button to fire the import, previously file selection and things have happened, so I can just call the backend URL (audit.import) with the correct parameters and the upload will happen and work. So what I have done, is create a URL to return the status of the upload from the server (loadprogress). The plan being that the loadprogress will be called via ajax and the magic of js setTimeout, in order to poll the backend. Once we see all records have been successful or not, then the poll can end.
The problem is, the loadprogress poll fires regularly, right up until I press the button to start the main file load. Then it fails to fire again until the main file load has completed, thus removing the planned use for the progress meter.
My javascript looks like this,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var fullname = '<?php echo $fullname; ?>';
$("#ajaxButton").click(function(event) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/audit.import/1/' + fullname,
type: 'POST',
async: true,
}).always(function(xhr, status) {
console.log("Import complete with status of " + status);
});
console.log("sent async call to perform audit");
});
(function loadProgress() {
$.ajax({
type: 'GET',
url: '/loadprogress',
}).done(function(result) {
console.log(result);
}).then(function() {
setTimeout(loadProgress, 100);
})
})();
});
</script>
I am on a mac in safari, but have tried chrome on mac with the same results.
Any assistance would be welcomed.
Thanks.
It was indeed a server side problem. I was running on a single threaded test server which means there was no second thread for my second process. Hence the block. By default the test Laravel server that comes with the install is only single threaded. A fact I had missed in my setup of the test server.

javascript/Ajax only working when debugging

I wanted to remove the user session and related data when the user closes the browser. i referred to this (http://weblogs.asp.net/kaushal/archive/2011/02/25/user-is-trying-to-leave-trap-and-set-confirm-alert-on-browser-tab-close-event.aspx) post and i have some coding as below. I wanted to delete the user data from the application state and SQL server database when the user closes the browser. And i am doing this with the help of a handler.
The below code is working fine while debugging, it is calling the handler and executing all the codes which i have written in to it. But when i really use this app this is not working. I don't know where the problem is. And it is eating my time.
(I am using this inside the content of a Master page)
window.onbeforeunload = confirmExit;
function confirmExit() {
var UserID = '<%= Session["UserID"] %>';
$.ajax({
type: "POST",
url: "../../Handlers/HandlerUser.ashx?Action=RemoveUserDataOnBrowserClose&UserID=" + UserID.toString(),
contentType: "application/json; charset=utf-8",
async: false,
success: function (data) {
}
});
}
if any one can suggest another way to achieve the same, it will be a great help.
My guess is it is not working because it is asynchronous call.
the function exits before the call happens.
I suggest you interrupt the closing action, clean the data from your database and than after in your callback you call the closing event programmatically.
I found this post which might help you.
At last i got the answer. My problem was my handlers were not calling and it was because i didn't add Forms Authentication to my app. I added this code after authentication and it worked fine.
FormsAuthentication.RedirectFromLoginPage(UserID, false);
I didn't knew that this was necessary.Thanks every one for helping me..

Page waits for AJAX before changing location

This question might seem a bit odd, the problem arised when the page went through webtests.
The page uses an AJAX call (async set to true) to gather some data. For some reason it won't swap pages before the AJAX call has returned - consider the following code:
console.log("firing ajax call");
$.ajax({
type: "POST",
url: "requestedService",
data: mode : "requestedMethod",
cache: false,
dataType: "json",
success: function() { console.log("ajax response received") },
error: null,
complete: null,
});
console.log("changing window location");
window.location = "http://www.google.com"
The location only changes after AJAX returns the response. I have tested the call, it is in fact asynchronous, the page isn't blocked. It should just load the new page even if the AJAX call hasn't completed, but doesn't. I can see the page is trying to load, but it only happens once I get the response. Any ideas?
The console output is:
firing ajax call
changing window location
ajax response received
This seems to work fine for me. The location is changed before the code in the async handler executes. Maybe you should post some real code and not a simplified version, so that we can help better.
Here is a demonstration that works as you expect: http://jsfiddle.net/BSg9P/
$(document).ready(function() {
var result;
$("#btn").on('click', function(sender, args) {
setInterval(function() {
result = "some result";
console.log("Just returned a result");
}, 5000);
window.location = "http://www.google.com";
});
});
And here is a screenshot of the result: http://screencast.com/t/VbxMCxxyIbB
I have clicked the button 2 times, and you can see in the JS console that the message about the location change is printed before the result each time. (The error is related to CORS, if it was the same domain, it would navigate).
Bit late but maybe someone else will have the same issue.
This answer by #todd-menier might help: https://stackoverflow.com/questions/941889#answer-970843
So the issue might be server-side. For eg, if you're using PHP sessions by default the user's session will be locked while the server is processing the ajax request, so the next request to the new page won't be able to be processed by the server until the ajax has completed and released the lock. You can release the lock early if your ajax processing code doesn't need it so the next page load can happen simultaneously.

Loading gif image is not showing in IE and chrome

I am using JQuery ajax call for sending synchronized call to server and want to display a loading image for that time.
But loading image is visible in Firefox but not in IE and chrome. When i debug, i found that in IE, when we call java script, it stop showing changes in browser as it halts DOM and when the call is completed, it then shows all the changes. Since i shows the loading image on ajax call and remove it after completing the call, the IE doe not display any image.
But when i use alert box,it shows the loading image in IE as it stop the thread until we response to it.
Is there any method to stop java script execution for a millisecond such that IE execution halts and loading image is shown.
I already tried ajaxSend, ajaxComplete, ajaxStart, ajaxStop of JQuery and timer event of java script, but does not get any solution.
Any help is precious, thanks in advance.
In the context of XHR, synchronously means just that the browser freezes until the request is complete. If what you want is to make sure only one request is running at a given time, then use your own flag to indicate that a request is in progress.
By definition, the synchronous flag of a request means that any other activity must stop. I'm surprised that it even works in Firefox, last time I tried that it didn't work, but that was a long time ago. So forget about it, there's no way to make it work in all browsers. Even if you delay the request using a setTimeout, at best you'll get a frozen browser with a non-animated gif. And users don't like when you freeze their browser, especially if the request might take more than a fraction of a second.
Don't ever depend on the browser for security or correct functionality related features. If your application might get broken if a client does two requests in parallel, then you have a bug on the server side. There's nothing that prevents a malicious user from making parallel requests using other tools than the normal UI.
You problem is probably the 'synchronized' part in your opening post.
Open the connection asynchronously. That stops the browser from locking up, and it will work as you expect. (set async = true on your XmlHttpRequest / activex object)
try to shows the loading image at the start of your ajax jquery call and hide it on success event
or
you can use set time out also
I also faced similar problem while working with ajax like i applied some styles to UI during ajax call but these are not applied to UI and same as you told that if we put some alert it will work as expected until OK is not clicked for alert
I can't guess why it happening but you can use JQuery to show or Hide that Loading.... div
Hope it will work....
I had a similar problem and then I sorted it out by using the Update Panel in ASP.NET. If you are using PHP or any other technology then you have to use ajax call. If you do synchronized call then the Loading image will not be shown.
I have had similar situation to deal with, if you have to make the synchronous call, browser will suspend the DOM manipulation. So unless absolutely necessary, keep with the async calls.
There is a workaround for manipulating the DOM and show an element before starting the ajax call. Use jQuery animate(), and make the ajax call in the callback for animation complete. Following code works for me:
//show the loading animation div
$('#loading').show();
//call dummy animate on element, call ajax on finish handler
$('#loading').animate({
opacity: 1
}, 500, function() {
//call ajax here
var dataString = getDataString() + p + '&al=1';
$.ajax(
{
type: 'GET',
async: false,
url: 'uldateList.php',
data: dataString,
dataType: 'json',
success: function(result){
//Do something with result
...
//hide loading animation
$('#loading').hide();
}
});
});
You can try to execute the ajax synchronous call in the image load callback.
Something like:
var img = new Image();
img.src = "loading.gif";
img.onload = function() {
/* ajax synch call */
}
Then append img to DOM.
Hi try to modify ajax call like this its works for me
xmlHttp.open('POST', url, true);
xmlHttp.onreadystatechange = myHandlerFunction;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader("Accept-Charset", "charset=UTF-8");
xmlHttp.send(query);
I used Sergiu Dumitriu's information as base. I set my async to true and added
beforeSend: function() {
$('#Waiting').jqmShow();
},
complete: function() {
$('#Waiting').jqmHide();
}
And it worked for me. Basically i created my own async:false attribute.
In your $.ajax call you need to add async: true. Following code works for me:
$.ajax({
url: 'ajax_url',
data: 'sending_data',
type: 'POST',
cache : false,
async: true,
beforeSend: function() {
$('#id_of_element_where_loading_needed').html('html_of_loading_gif');
},
success: function(data) {
$('#id_of_element_where_result_will_be_shown').html(data.body);
}
});

Keep Track Of Ajax Request

Newbie here..
I just want to ask how can I accomplish my homework in school.
I basically have this need.
I want to send an ajax request every 10 seconds but I dont want to initiate another request if my previous request has not returned yet.
I am thinking that the connection to DB might be that bad sometimes so I would like to wait for my previous request to be finished (success/failed/error) before I fire up another.
I check on javascript and and found the setinterval method. But how can I line up my ajax request so that the server doesnt get fired up by many ajax request?
I am studying jquery right now and is using JSON.
One method would be to set a variable to false when you send out a request. When you get it back set it back to true. When you go to send out a new ajax request make sure the value is true. If not add it to a queue of some sort so that it will be called when the request is finished. However if every request takes longer then ten seconds your queue will get pretty backed up. So you may not want a queue. So instead when you go to send out the ajax request if the variable is false you just wait another ten seconds.
I'll even help more:
var isWatingForResponse = false;
$.ajax({
url: 'wherever'
,dataType: 'json'
,beforeSend: function() {
if(isWatingForResponse) {
return false;
}
isWatingForResponse = true;
}
,complete: function() {
isWatingForResponse = false;
}
,success: function (data) {
//process data
}
});
Or follow #qw3n answer. This should work with jQuery 1.4.2
As I see the OP question:
How to set up fault-tolerance on the client-side because of Db-server issues, using jQuery Ajax?
This IMHO, is a really good question.
If I may, I would like to map out the pipe:
web-client->network->web-server->network->Db-server
Db-server->network->web-server->network->web-client
Your solution to this problem of handling issues with the db-server in the client is workable, but really does not address the actual problem. It could really cripple you for future extension of your client.
You should really be handling this issue as close to the problem as possible. In the web-server.

Categories