Search code examples
jqueryjsonp

The ajaxSend event is not firing for ajax requests with datatype jsonp. How to make it fire?


I am trying to debug all of the jquery requests on my page but for some reason the requests with datatype jsonp are not causing my global event to fire. I have no control over the ajax requests that are using the jsonp datatype so I need to come up with a solution that wont require changing the actual ajax request code. I can however make changes to the $.ajax function/jquery lib etc. I have a stripped down example that shows how it the event is not being triggered.

$('body').bind("ajaxSend",function() {
    alert('global ajaxSend');
});
$.ajax({
    type: 'GET',
    url: 'http://www.example.com',
    dataType: "jsonp",
    success : function(result) {alert('success');},
    error : function(XMLHttpRequest,textStatus,errorThrown) {alert('error');}
});

In that example the ajaxSend event is not triggered. Does anyone know of a workaround or patch that will make it fire?


Solution

  • A jsonp request works by inserting a script tag in the DOM, so it won't fire the error handler, and probably not your global ajaxSend handler either.

    Have'nt tried it, but you could always try triggering the event in the success callback:

    $.ajax({
        type: 'GET',
        url: 'http://www.example.com',
        dataType: "jsonp"
    }).done(function() {
        $('body').trigger('ajaxSend');
    });