tags:

views:

32

answers:

2

I have to modify a project written by someone else. Because the code is a mess i can't really change this $.post() (or replace it by $.ajax()). What i need to do, is to know if the post returns something else then json and return it.

$.post('balbal.html', json, function(data) { ... my coude ... }, 'json')

I can see the post response i the console.log. Is there a simple way to retrieve it?

A: 

You can use $.ajax() ($.post is a shortcut that ends up calling it anyway), and define the error callback.

Or, if you really do not want to do that, call

$.ajaxError(function(){
   //error handler
})

before that $.post

Victor
there is no error callback on $.post() ?
meo
http://api.jquery.com/jQuery.post/ There is no error handling in `$.post` because it is just a shortcut method to save typing.
Victor
i tried the ajaxError but it seams not to execute. I get a answer form the post but its, a php error and not the json i expect.
meo
Then hijack the success handler and add a check there first. Something will get called, no? :P
Victor
it seams not to enter the success handler if the response is not json.
meo
+3  A: 

There's a couple of ways to do it, but if you're not getting the error response available through the returned JSON data object, you can use $.ajaxSetup() to define defaults for all ajax calls through jQuery. Even though the $.post() method doesn't specify an error handler or callback in and of itself, the $.ajaxSetup() method will capture any ajax faults and execute the function you define for it.

Alternatively, there is also an $.ajaxError() function that will do the same sort of thing.

Note that this will not work if your JSON response is returned correctly but with a server-side error code. If you want to capture these sorts of cases, you might be best to look for them using the $.ajaxComplete() method

Phil.Wheeler
it worked with by setting the default error function with $.ajaxSetup()...
meo