Tschef
Tschef

Reputation:

Get the response data into the jQuery ajaxComplete function

What I would like to do is send the return data from any ajax call and also have it available in the ajaxComplete function.

So when I have a $.post or $.get or $.getJSON and so on request like this:

$.post(url, options, function(DATA)
{
    $('output').html(DATA);
});

I also want to get the same data into:

$.ajaxComplete(function(event, XMLHttpRequest, ajaxOptions)
{
    // do something with DATA that is returned by the ajax request
    alert(DATA);
});

It means I want in the global ajaxComplete function also the same data which I get when I call one of the ajax functions.

Upvotes: 12

Views: 24209

Answers (3)

Derek
Derek

Reputation: 4751

You can convert to JSON inside your ajaxComplete function by using

$.parseJSON(xhr.responseText);

Upvotes: 11

redsquare
redsquare

Reputation: 78667

XMLHttpRequest.responseText

Note that if you set the dataType in the call to json or are using the getJSON function you will have to copy what jquery does internally and use eval( '(' + data + ')' ) to get the data into json so that it mirrors the data param passed to the success callback.

Or as activa points out just call the internal method to save the work.

Upvotes: 8

Philippe Leybaert
Philippe Leybaert

Reputation: 171764

There's no easy way to do that, but you could extract the data from the xhr object. jQuery includes an internal function that does just that, but it's undocumented.

You can call this method like this:

$.ajaxComplete(function(event, xhr, options)
{
    var data = $.httpData(xhr,options.dataType);

    alert(data);
});

But beware: this is valid in jQuery 1.3.2, and because it's undocumented, it can change in future releases of jQuery.

Upvotes: 1

Related Questions