Friday 2 July 2010

.ajax beforeSend Doesn't Fire

I absolutely adore jQuery but there are some things that are just plain hard to do with the current version. One of those is cross-domain (JSONP) requests. No only is the setup convoluted but the requirements are exacting to arrive at a working solution for something that should be (?) reasonably simple. But I'll save the details for another time—for now, just know I'm building with jQuery and using JSONP to issue cross-domain requests.

Under the covers, that cross domain request is actually being issued by dynamically loading a new script tag in the DOM, even though everything's still handled through the $.ajax() function. It's workable, of course, but since there are no XMLHTTPRequests involved, the behaviour is apparently somewhat different. In my particular case, I was wiring up  'beforeSend and 'complete' event handlers to show and hide a spinner across the lifetime of the request; the 'complete' handler was firing fine but the 'beforeSend' handler wasn't firing at all.

A response by SLaks to a Stack Overflow post reminded me the request mechanism with JSONP is different and implied 'beforeSend' wouldn't work with this setup. His response instead suggested showing the spinner after the $.ajax call and this did the trick for me. 

2 comments:

  1. I fkn love you dude...
    You have any ideas on whats wrong with the beforesend option on ajax?
    It took me two hours of trial and error just to get to tis post...

    ReplyDelete
  2. @Daniel: It's been a while but from memory it's due to the fact you're not dealing with an XMLHTTPRequest--you're not sending anything. So nothing really "wrong" with beforeSend because beforeSend doesn't know about this technique (at least when I wrote this post...). Good luck and thanks for commenting!

    ReplyDelete

Spam comments will be deleted

Note: only a member of this blog may post a comment.