views:

38

answers:

3

Say I have this code:

function onComplete(event, request, settings)
{
    // How do I get the data? In the correct format?
}

$('body').ajaxComplete(onComplete);

In regular ajax success handlers, I can just access the data directly since it will be the first parameter to the handler. It will also be in the correct format (as long as the content-type was set right on the server).

How do I deal with the data on the ajaxComplete event?

A: 

According to the the doc:

http://api.jquery.com/ajaxComplete/

I don't think you mean to fiddle with the data, because it doesn't pass any data to the handler. If you want data you better off using the set success property in regular Ajax.

vito huang
Thing is that the case I want to cover is when the success handler isn't called because the request.status will be different than 200.
Svish
A: 

This may not be the right handler to use if you want to get data as this is really intended more as a basic notification callback (for all hooked elements) when any AJAX calls completes.

To get to your data you should you might need to be more targeted in your approach and use the $.ajax() call or one of its variants like $.get() or $.getJSON(). See here

bjg
I already do handle the data where appropriate, except when there is a failure. When there is a failure I send json encoded error messages from the server with a status of 400 or 404 depending on what's appropriate. And I want to display those messages.
Svish
+2  A: 

You can use it like this, but it's not documented:

function onComplete(event, request, settings) {
  var data = $.httpData(request, settings.dataType, settings);
}

The jQuery.httpData function is what's used internally to get data for the success handler, but you can use it directly. Please be aware that it is undocumented, and therefore subject to change without notice in new releases. For example in jQuery 1.4.3, it will be jQuery.ajax.httpData instead.

Nick Craver
+1 - seriously, you're doing too much jQuery core research in your spare time :p
jAndy
@jAndy - Actually I just have to occasionally look for *why* something's happening, whether it's for a project I'm on or a question here...but jQuery isn't *that* large, you remember most of it after a while :)
Nick Craver
Seems to work nicely! Will just have to remember this when it breaks in the new version :p
Svish