0

I am getting sometimes bad response data or undefined or null or empty string as response. I am checking whether my response is of json before proceeding with further data manipulation.

function response(oResponse, xhr) {
    var ct = xhr.getResponseHeader("content-type") || "";
    if (ct.indexOf('json') > -1) {
        // ...
    }
}

I want to check whether the response is valid before proceeding. I want to check for invalid responses like "null", "undefined", "emptry string" too along with checking whether the response is json before manipulating the data.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Shane
  • 5,517
  • 15
  • 49
  • 79
  • 2
    Okay, what's the problem? – Matthew Mar 30 '15 at 14:23
  • I want to check for invalid responses like "null", "undefined", "emptry string" too along with checking whether the response is json before manipulating the data. – Shane Mar 30 '15 at 14:33
  • http://stackoverflow.com/questions/7662620/best-way-to-find-out-if-response-is-json-during-ajaxsuccess --> this has a good way of going about it. I think the second part to your question could be answered by checking if the responseText is empty (or if the responseHeader attribute that you're looking for is empty/null/etc) -- ex: !xhr.responseText – Brodie Mar 30 '15 at 14:44

1 Answers1

0

Take a look to the snippet below

var xhr = new XMLHttpRequest();
// ...
xhr.onreadystatechange = function () { 
  var response = JSON.parse(xhr.responseText);
  if(response && typeof response === "object" && response !== null){
    // you're getting data in JSON
  }
}
hex494D49
  • 9,109
  • 3
  • 38
  • 47