I have a page where I show 5 questions to a user and when he clicks on Next 5 link I am sending the score of current page onbeforeunload() to the script updateScore() asynchronously using jQuery AJAX and when the call is successful the next 5 questions are displayed.
window.onbeforeunload=function()
{
$.ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
cache: false,
timeout:5000,
async:false
});
}
But the problem is that on slow connections,it might hang the browser for a while until AJAX call returns successfully.When I tried async:true(default) the next page is loaded first without making call to updateScore.php.It might be due to the fact that connection is fast in localhost hence giving no time for the AJAX call to complete.This was the reason I used async:false.Will it happen (making no AJAX call) if I use async:true in practical case as well?If yes, is there a way to come around this problem?
I advice you to change your code a bit.
Make ajax request on "click" event, and redirect user inside ajax callback function.
Like this:
$('#mybutton').on('click', function()
{
$('#pleasewait').show();
$ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
success: function() { document.location="nextpage.php" }
});
}
Related
I have a function on the server to create hundreds of elements and store them in the database. This action takes time on the server and when the action finalize, it returns the result. The problem is that Ajax terminates the request after around 150000ms with Bad Request 400 and the runningProcess response.
The Ajax call is:
showProgressCursor();
$.ajax({
type: "POST",
url: strUrl,
data: {accountId: byId("account-id").value},
dataType: "JSON",
success: function (oResult, strTextStatus, internalResponse) {
console.log("Success")
_showTheResult(oResult, strTextStatus, internalResponse, allDataError);
hideProgressCursor();
},
error: function(oResult) {
manageError(oResult);
console.log(oResult);
hideProgressCursor();
}
});
Do you know how I can increase this time or cancel it until Ajax receives an answer?
Extra: at the moment, I am showing a loading wheel but it would be better if I show a bar with the progress of the operation, could I show something like that? (I have thought of making a different recurring request (every second for example) and obtaining the total created and the total to be created and thus be able to have the progress. I don't know if this is a good solution)
I have a method which checks for notifications and executes a js.erb in return.
The JS which is triggering this method is given below:
setInterval(function () {
$.ajax({
url: "http://localhost:3000/checkNotification",
type: "GET"
});
}, 15000);
This is working great but I am worried about the performance of the site once it will be in production.
Will this cause a performance issue?
If yes, is there another way to solve this problem?
one suggestion I would make is to take advantage of the callback function of ajax so that if a request takes longer than expected it will not fire again until the last one completes
function checkNotifications(){
$.ajax({
url: "http://localhost:3000/checkNotification",
type: "GET",
success: function(){
setTimout(checkNotification, 15000);
}
});
};
also if for some reason the server were to respond with a 500 error, it would prevent the function from continuing
Probably best to revise the question:
I have an ajax call in my code and I want to cancel the call immediately after it is sent. Basically, I don't want to wait for a response, I just want the entire request to be sent from the client. Could anyone provide some ideas on how to accomplish this?
I have tried the following in Chrome, however it seems that the request is never actually sent (I am logging received requests on the server side).
Basically:
var sendRequest = jQuery.ajax({
url: '/awesomeness.txt',
dataType : 'json',
timeout: 2000,
cache: false,
success: function(result) {}
});
sendRequest.abort();
I have also tried setting a timeout of 1, but bizarrely if I load the page from a new browser the request is not sent (if I refresh the page it is sent).
As easy as just:
jQuery.ajax({
url: '/awesomeness.txt',
dataType : 'json',
timeout: 2000,
cache: false,
afterSend: function() {/*run awesome code*/}
success: function(result) {}
});
// call whatever you want after send
afterSend();
So there is no built in jquery.ajax event for that but you may just call the function right after $.ajax();
Just call YOUR_COOL_FUNCTION after your code block.
This will work because ajax requests use callbacks, so it will not block the current execution for the sake of the performed request, but it will make the request, then move on to your code, so it's as simple as putting any desired block of code after this AJAX call.
I have this function to unlock a list the user is currently editing:
function unsetLock(id) {
$.ajax({
type: "POST",
url: "/ajax.php?action=unsetLock",
dataType: 'json',
data: "id="+ id
});
return true;
}
When the user navigates away from the list, I have to cancel the lock:
unsetLock(lockID);
document.location.href='/page/to/navigate/back/to.php';
However this unlock sometimes works and sometimes doesn't. I think it is because document.location.href is executed, before the ajax call has actually been sent to the server.
How can I force to send the unlock before navigating the user to the next page?
Actually I don't need to wait for the Ajax-Reply, since I want to redirect the user, whether it succeeds, or not. I just want to make sure, it is being transferred to the server.
If I place the document.location.href inside the Ajax function, it will wait for the reply.
A really bad-mannered way to do it is to add: async: false, which will lock the browser up until the AJAX call is complete.
Of course, if there is a problem and the AJAX call never completes...
It's the quickest and easiest solution to your problem, but probably not the best.
I, personally, would have the lock only last for twenty seconds (using a timestamp in the database), and send an ajax call every ten seconds to re-lock the page (if that makes sense) using setInterval().
That way the lock will unset itself a few seconds after someone leaves the page, and is good no matter what the situation (a power failure for the client wouldn't leave the page locked forever, for example).
Perhaps I'm missing something, but why not use the success option in the Ajax call? This will execute whatever the outcome and makes sure it reaches the server.
function unsetLock(id) {
$.ajax({
type: "POST",
url: "/ajax.php?action=unsetLock",
dataType: 'json',
data: "id="+ id,
success: function(){
document.location.href='/page/to/navigate/back/to.php';
}
});
return true;
}
I have the following code:
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function () {
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
});
When a user changes some data the code updates the database. There is code that comes before this that picks the data values and it all works good.
When the user changes the Position column the database gets changed and I wanted to trigger a refresh of the screen (it's a report screen sorted by position). The refresh works but it seems like it is out of sync. I have the location.reload() in the success area but is it possible that is getting run before the Ajax has completed?
Is it possible that this kind of refresh is taking place before the database has been properly updated? When I do another refresh of the page manually from the browser the data always appears in the correct order.
Your document is cached. You shouold use
location.reload(true)
to realod with clear cache.
AJAX is asynchronous by default. Once the call is issued, the rest of your code will continue executing. If the value of location gets changed before the ajax call returns its data, the success function will be using the current-at-the-time-it-executes value of location, which is now something different than what it was when the ajax call started.
The success code will not run until the ajax call returns, so that's not the problem. but you're depending on location not being changed between the time you start the ajax stuff and the time it completes.
there is a API in jquery ajaxComplete. whenever a ajax call will be completed this will be invoked.
$.ajaxComplete(function(){
//do something
});
reference : http://api.jquery.com/ajaxComplete/
Whatever you write inside the success handler will be executed only after the completion of the ajax request you made to the server page. so you can load the updated content in that handler.you can use a parameter to accept the response from your success function and check whether your transaction is success or not.
From your server page, after making the database update,you can return true or false.
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function (data) {
// This will be excuted only after you receive a response from your server page
if(data=="true") //db updated properly
{
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
else
{
alert("Error in updating the data");
}
}
});