Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery AJAX and handling different dataTypes
    primarykey
    data
    text
    <p>I'm using ASP.Net MVC, but this applies to any framework. </p> <p>I'm making an Ajax call to my server, which most of the time returns plain old HTML, however if there is an error, I'd like it to return a JSON object with a status message (and a few other things). There doesn't appear to be a way for the <code>dataType</code> option in the jQuery call to handle this well. By default it seems to parse everything as html, leading to a <code>&lt;div&gt;</code> being populated with <code>"{ status: 'error', message: 'something bad happened'}"</code>.</p> <p>[Edit] Ignoring the <code>dataType</code> object and letting jQuery figure out doesn't work either. It views the type of the result as a <code>string</code> and treats it as HTML.</p> <p>One solution I came up with is to attempt to parse the result object as JSON. If that works we know it's a JSON object. If it throws an exception, it's HTML:</p> <pre><code>$.ajax({ data: {}, success: function(data, textStatus) { try { var errorObj = JSON.parse(data); handleError(errorObj); } catch(ex) { $('#results').html(data); } }, dataType: 'html', // sometimes it is 'json' :-/ url: '/home/AjaxTest', type: 'POST' }); </code></pre> <p>However, using an Exception in that way strikes me as pretty bad design (and unintuitive to say the least). Is there a better way? I thought of wrapping the entire response in a JSON object, but in this circumstance, I don't think that's an option.</p> <p>Here's the solution that I got from Steve Willcock:</p> <pre><code>// ASP.NET MVC Action: [AcceptVerbs(HttpVerbs.Post)] public ActionResult AjaxTest(int magic) { try { var someVal = GetValue(); return PartialView("DataPage", someVal); } catch (Exception ex) { this.HttpContext.Response.StatusCode = 500; return Json(new { status = "Error", message = ex.Message }); } } // jQuery call: $.ajax({ data: {}, success: function(data, textStatus) { $('#results').html(data); }, error: function() { var errorObj = JSON.parse(XMLHttpRequest.responseText); handleError(errorObj); }, dataType: 'html', url: '/home/AjaxTest', type: 'POST' }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload