0

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?

Naveen
  • 7,944
  • 12
  • 78
  • 165
  • 1
    why are you using `onbeforeunload` event in the first place? cant you use regular methods of binding an `a` element and to get the next five quesition on JSON format which is quicker and have nicer look (the user never leaves the current page, hence all the side scripts, css, etc loading only one time) – JohnnyJS Feb 12 '14 at 12:49
  • I agree to @JohnnyJS. And you are doing double job here... Instead of sending data with POST u send it via ajax and then reload anyway... – Vygandas Feb 12 '14 at 12:51
  • @JohnnyJS : This is due to http://stackoverflow.com/questions/21230158/does-using-ajax-on-your-website-drop-your-page-views-while-ranking asked earlier by me. – Naveen Feb 12 '14 at 12:58

1 Answers1

0

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" }
  });
}
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193