Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the response content-type from jQuery.Post

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.

like image 591
Chao Avatar asked Dec 06 '25 11:12

Chao


1 Answers

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
  }
});
like image 195
Nick Craver Avatar answered Dec 08 '25 01:12

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!