1

I have a few menu items on the left side of the screen, each opens a new page on the site. On one of the pages there is an async ajax call to python that successfully returns a bunch of data.

However, when I open this page and quickly click on another menu item to open another page without waiting for the ajax request to finish, I receive an [Object object] error.

postData = {"userid":userid, "current":dict_current, "step":dict_step};

$.ajax({
    url: "/cgi-bin/get_dictionary.py",
    type: "post",
    datatype:"json",
    async : true,
    data: {postData},
    success: function(response){
        //parse json
        var json = $.parseJSON(response);
    } 
})
.fail(function(err) {
    alert("error" + err); //[Object object]
});

So I guess, I should somehow abort the request when I open a new page, but how do I access that request?

What is the best thing to do here?

erdomester
  • 11,789
  • 32
  • 132
  • 234

1 Answers1

1

add a variable name for your ajax request. define variable first.

var ajaxreq;

then use that variable for your ajax request:

ajaxreq = $.ajax(...);

and abort that ajax on page unload:

$( window ).unload(function() {
  ajaxreq.abort();
});
Armin Nikdel
  • 315
  • 2
  • 9
  • 1
    unload did not work, but `window.onbeforeunload = function() {ajaxreq.abort();}; did`. Thanks! But honestly the easiest solution is to don't alert the error. Question is if it's okay when it comes to performance – erdomester Apr 03 '16 at 14:54