0

My application making an ajax POST to server, and if the server validation fails, server returns string or Dictionary<string, object> back to client.

So if server is sending Dictionary then the serialized responseText that jQuery is receiving something like

"{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}"

i also have corresponding responseJSON available on client side.

    $.ajax({
        cache: false,
        type: 'POST',
        url: url,
        data: data            
    })            
    .fail(function (response, textStatus, errorThrown) {           
            if (response.status === '400') {
                if ($.isArray(response.responseJSON)) {
                    $.each(response.responseJSON, function (index, value) {
                        //do something
                    })
                }
                else if ($.type(response.responseJSON) === 'string') {
                      // do something
                }
            }               
        }

The .isArray method returns false when response is dictionary. How do i determine if responseJSON is Dictionary and how do i loop?

Note
object that server is sending back

LP13
  • 30,567
  • 53
  • 217
  • 400
  • Possible duplicate of [Check if a value is an object in JavaScript](http://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript) – Hamms Apr 13 '17 at 21:43
  • There are no such things as `Dictionary` types in JavaScript. You are getting a JSON string either way. Once deserialized, you have an `Object`. – Scott Marcus Apr 13 '17 at 21:45
  • What you are doing doesn't make sense. Set the dataType as json and use success handler to work with the data which will already be an object. If `fail` fires then either the responseText wasn't valid json or there was some other connection error – charlietfl Apr 13 '17 at 22:14
  • @charlietfl That is not true. I am using asp.net core on server side. I have global handler on server side which validates POST object and if not valid it returns error as bad request. So it happens before any MVC action gets executed. Is such case `fail` will get fire with status code `400` – LP13 Apr 14 '17 at 04:20

1 Answers1

0

You try to interpret the response and see if it ends up being an object (or "Dictionary"). If the response appears to be JSON, and the result of it is also an object ("Dictionary"), then you know the string was an object ("Dictionary").

The code below should outline all necessary techniques for you to integrate it into your own code.

var thatResponseJson = "{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}";
try {
    var result = JSON.parse(thatResponseJson);
    if (result instanceof Array) {
        // An Array
    } else if (typeof result === 'object' && thatResponseJson[0] === '{') {
        // Usually an object
    } else if (typeof result === 'string') {
        // A string
    } else {
        // Neither an Array, some other kind of object, or a string
    }
} catch (err) {
    // Not valid JSON
}
Brian
  • 7,394
  • 3
  • 25
  • 46
  • No need for most of this. `$.ajax` will validate the json internally when set `dataType:'json'`. Won't get to `fail` if valid json returned and no CORS issues. In addition can use jQuery core `$.type()` utility ..will return object vs array vs string http://api.jquery.com/jQuery.type/ – charlietfl Apr 13 '17 at 23:04