Avoiding jQuery Ajax errors from leaving the page in the middle of a request

Sunday, 22 July 2007

I was having a problem with my jQuery Ajax on another site. The request went fine but if the user left the page before the request returned, it would call the Ajax error function. Frustrating since there was not necessarily any error, just the request was getting stepped on before it could return as successful.

Took quite a bit of searching to get the clues to figure out what to do. Since I could not find it as a “complete answer,” I present it here for the next sucker who is getting an Ajax error when the user leaves the page. The solution bits are in bold.

I don’t know for sure it’s cross-platform but it works great in Firefox and the most recent Safari.

<script type="text/javascript">//<![CDATA[
$(document).ready(function() {
  function doSomething (arg) {
    var myData = new Object({ "data":arg });
    var req = $.ajax({
                url: "/location/location/location"
              ,type: "POST"
          ,dataType: "json"
              ,data: myData
           ,success: function(json){ somethingSomething }
             ,error: function(xhttpreq,err){
                       alert("There was an Ajax error.")}
          });
    $(window).bind("beforeunload", function() { 
      req.abort();
    });
  }
  doSomething("info to send");
});
//]]> </script>
digg stumbleupon del.icio.us reddit Fark Technorati Faves

Discussion

Comments


Jen

Re: Avoiding jQuery Ajax errors from leaving the page in the middle of a request

Have you ever had to implement something like a progress bar using Ajax? I mean, like getting and using intermediate data before all of the response is ready? I was pulling my hair out over this a couple of weeks ago. There's a Big Red Button on the site I'm working on that sets off a big process on the server. The process usually takes 15-45 seconds to complete, and the user has to just sit around and wait for it complete. I wanted to display some status updates as the process was progressing... and that turned out to be much harder to implement than I expected.

It was a breeze to do in Firefox... I just waited for my xmlrequestobject's ready state to be 3 and took the data from there (Every time there was an update, even though the ready state didn't change, onreadystatechange was called, which was great). But... IE doesn't let you take any data until the entire response is ready and you're in ready state 4.

Why??!! Why? Why? I don't understand... once it's sent, you can't take it back, so what possible reason could IE have of denying me this data? Grrr...

Anyway... I finally came up with a really convoluted way of making it work in IE, and it ended up being too big of a headache to use on our site. Have you had to handle intermediate ajax data?

By Jen on 22 July 2007 · 17:59
comment link · reply to this

Ashley

Re^2: Avoiding jQuery Ajax errors from leaving the page in the middle of a request

Nerd.

By Ashley on 22 July 2007 · 18:26
comment link · reply to this

Ashley

Re^2: Avoiding jQuery Ajax errors from leaving the page in the middle of a request

No, but seriously. I played around with some raw Ajax at first like a year ago because I figured I needed to know it at least a little. I hated it for exactly the reasons you’re having problems. I got something working right in Firefox, it wouldn’t work in Safari. Working in Safari, wouldn’t work in IE. So I have no insight for you. I quit screwing around with it for several months b/c of the x-compat issues.

I heartily recommend a JS library. Do not do it raw. There’s simply no reason when there are now several very good libraries that abstract it so you can just write code that will work in all the major, current browsers. If it’s at work, explain to them how much time and trouble it will save even if it’s little painful at first.

Roughly in order of (personal) preference–

Probably should avoid Prototype. It was the big one for awhile but a couple hackers I respect immensely hate it and I learned to trust them b/c when I don’t I end up wasting tons of time.

By Ashley on 22 July 2007 · 18:27
comment link · reply to this

Ashley

Re^3: Avoiding jQuery Ajax errors from leaving the page in the middle of a request

Quick update. Ext JS is pretty hot; number one for big stuff. I still like jQuery better for inline and small stuff. Its syntax is simply too sweet for words. There is also YUI but I think I hate it in comparison to Ext JS which grew out of it. The Yahoo guys seem to have been addled by the PHP.

By Ashley on 27 January 2008 · 23:58
comment link · reply to this

James Hargreaves

Re: Avoiding jQuery Ajax errors from leaving the page in the middle of a request

Brill, thanks. I was trying the same with the "unload" event, but that wasn't working. Seems the "beforeunload" event is what I needed :)

By James Hargreaves on 12 January 2010 · 03:51
comment link · reply to this

Nelson Puglisi

Re: Avoiding jQuery Ajax errors from leaving the page in the middle of a request

Here is a solution a little more versatile

By Nelson Puglisi on 14 November 2012 · 19:16
comment link · reply to this

Your information (required) Name*
Email*
Website

* Indicates required fields; email is used for validation and is not displayed on the site.

Your comment
Commenting on Avoiding jQuery Ajax errors from leaving the page in the middle of a request
Title

Body is limited to ≈1,000 words. Paragraphs—but not line breaks—are automatically inserted. Valid XHTML is required. These are the allowed tags–

<a href=""></a> <br/> <acronym title=""></acronym> <abbr title=""></abbr> <code></code> <pre></pre> <tt></tt> <ins></ins> <del></del> <hr/> <cite></cite> <b></b> <i></i> <sup></sup> <sub></sub> <strong></strong> <em></em> <h1></h1> <h2></h2> <h3></h3> <q></q> <blockquote></blockquote>