1

I met a problem of http requests with redirect. Like this:

There is a button on page A, if you click the button, it triggers:

  1. Send multiple HTTP requests to the remote server to remember this click event
  2. Redirect to the page B

The problem is: The events N.1 above is not finished yet, but the page A is already redirected to page B.


I tried to test this behavior in Chrome, it shows status 200 for all the http requests of events N.1 above. But in Firefox, nope, I tried to use firebug to debug and selected the persist option to keep all the requests in the network, but there are not requests in the list.

So I have two supposes:

  1. Configuration of firefox is not right
  2. Thoses requests in Chrome are just "happened to" finish, good luck.

Please somebody can give me some tips or answers to figure it out ? Thank you

Leyla Lee
  • 466
  • 5
  • 19

2 Answers2

0

You should work with callbacks.(These are functions, which are triggered when something is finished - in this case a http request) If you're using jquery you could use this code:

$.ajax(
    {
      type:'GET',
      url:'/someurl',
      data:"someData=12345&someOtherData=foo",
      success: function(data){
        // do something - for instance your second http request
      },
      error : function(data){
        //something didnt went quite well
      }
    }
);

When you dont use jQuery, this function might come in handy (if you want to add Data like in the first example you have to add a querystring to the url-parameter):

function callAjax(url, callback){
    var xmlhttp;
    // compatible with IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

You can interleave such calls until you get to your final redirect-call. But beware, you dont want to end up in a callback hell

Community
  • 1
  • 1
InsOp
  • 2,425
  • 3
  • 27
  • 42
  • Thank you for your reply ! I like your answers, but it is not suitable in my situation: i would like to improve the code of sending the requests of events N.1 without changing the code of redirect. – Leyla Lee Aug 30 '16 at 15:42
0

I suggest you work with Promises.all or jquery.when

Prevent the click event to bubble up and then make the ajax requests and pass them as an array of promises.

chchrist
  • 18,854
  • 11
  • 48
  • 82
  • Thank you for your reply! Unfortunately, neither of two are used in the code. – Leyla Lee Aug 30 '16 at 15:35
  • then you callbacks as explained in the other answer but be aware of the pyramid of doom https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming) – chchrist Aug 30 '16 at 15:39