Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell whether the returned data of a successful $.ajax() is of html or json?

Tags:

jquery

I have a form that gets submitted to the server via jQuery .ajax() POST. If the form passed the validation on the server-side, the server would return result in HTML for the client-end to update its presentation accordingly. If, however, the form failed the validation, the server would return result in JSON, which consists of the validation errors.

Both types of result would end up in the success handler of .ajax(). Since both types are possible, the handler needs a way to determine whether the result is HTML or JSON. How can I do that?

Note: On the surface, my question looks like the same as this existing SO question but they are not the same. In that question, there's only one possible datatype (HTML or JSON), while my problem is about finding a way to deal with two possible datatypes (HTML and JSON).

like image 258
tamakisquare Avatar asked Apr 16 '12 17:04

tamakisquare


1 Answers

If you leave the dataType parameter blank, jQuery will determine this based on the MIME type:

dataTypeString

Default: Intelligent Guess (xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response

ref: http://api.jquery.com/jQuery.ajax/

like image 53
Ropstah Avatar answered Sep 29 '22 10:09

Ropstah