views:

23

answers:

1

Here's the thing, I have a jquery click event handler, that calls a post on click.

The type that it expects (4th parameter of $.post()) is "json". However, on the server side; there are two responses to the post: it's either json or html response. The problem is, if it returns html, the callback function isn't called (because the $.post expects a json?).

How can I react to this? I want something that if the server side script returns a json, execute callback, otherwise do another. Is that possible? Can I check the response type with $.post?

+2  A: 

You'll most likely want to use the generic jquery.ajax function. In particular the dataType: 'text' property should allow you to parse your return value in whatever method works for you. You can also use the parseJSON function

$.ajax({
  url: 'url',
  type: 'post'
  dataType: 'text',
  success: function(text) {
     if  (json) {
         var obj = $.parseJSON(text);
     } else {
         var html = $(text);
     }
  }
});
bendewey
What I did was to assign $.parseJSON(text) to a variable, surrounded by try catch (parseJSON will throw an exception if text isn't well formed json). Thanks for leading me to the answer anyway.
mives