views:

38

answers:

2

Is there a way when using jQuery.Post to discover the content-type of the response?

I have a form in a modal window and the idea is that if the form is not valid then an HTML snippet is sent and the contents of the modal are replaced with this snippet, if it is valid I want a simple string with the content for a flash notification (of the type used here on SO).

Currently I am testing if the returned string begins with "success" and if so using the rest of the string as the flash notification. This is obviously quite a hacky solution and I really don't like it.

Ideally I'd like to be able to have a conditional on the response and if it is "text/html" then insert the snippet, if it is "application/JSON" then I can not only send a message for the helper but potentially other data (message, id, more specific type of success/fail message etc) that would be helpful for extending to other forms in the future.

A: 

From the jQuery doc about post:

jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )

So you can get the XMLHttpRequest object, with which you can get information about the request (for example getAllResponseHeaders() method).

bazmegakapa
+2  A: 

jQuery will already detect and convert the response based on the content type header (if no type is specified on the $.ajax() call). For example: if it finds "json" in the content-type header, it'll be an object. You can just do this:

$.post("myPage.html", { name: "value" }, function(data) {
  if(typeof(data) === "string") {
    //html
  } else {
    //JSON
  }
});

Or, always pass back JSON, and have the notification message as a property on it, for example:

$.post("myPage.html", { name: "value" }, function(data) {
  if(data.notification) {
    showMessage(data.notification);
  } else {
    //use the data object
  }
});
Nick Craver
Urgh, typeof, of course, thanks for the answer.
Chao