2

I have this ajax request to get the data from my server, and the dataType is always html by default. But sometimes it would return json from the server, so I want to check if the returned data is html then execute A else execute B. Is it possible?

My jquery,

 $.ajax({
     type: "GET",
     dataType: "html",
     url: request_url,
     context: $('#meat'),
     async: true,
     beforeSend: function () {},
     success: function (returndata, status, jqXHR) {
         if ($.parseJSON(returndata) === false) A;
         else B.
     }
 });

I get this error when the returned data is html,

SyntaxError: JSON.parse: unexpected character

So how can I make this code versatile?

3
  • be sure you are parsing array to the json_encode() ? Commented Dec 23, 2013 at 12:15
  • yes for the json data. but i dont use json_encode if the returned data is html. Commented Dec 23, 2013 at 12:15
  • 1
    you can try this: dataType: "json" || "html", and you can try using typeof() method for the return data that if that is object the process it as json. Commented Dec 23, 2013 at 12:18

3 Answers 3

6

I'm not sure if there is a better way, but you could try... catch

$.ajax({
      type:       "GET",
      url:        request_url,
      context:    $('#meat'),
      async:      true,
      beforeSend: function() {
      },
      success: function (returndata, status, jqXHR) {
        var parsed;
        try
        {
            parsed = $.parseJSON(returndata);
            // Execute B
        }
        catch(e)
        {
           // treat as html then
           // do parsing here
           parsed = returnData;
           // Execute A
        }
      }

});
Sign up to request clarification or add additional context in comments.

Comments

4

Essentially, your code is just plain wrong - your serverside API is violating all principles of predictability if the return type can vary in an inconsistent manner. Your code should never have to guess at the type of the returned data.

Having said that, a simple try/catch will help as a workaround for the erratic behaviour if you don't want to fix it. Ie.

try {
    if ($.parseJSON(returndata) === false) A;
} catch(e) {
    // Treat as HTML here.
}

It's not pretty, but that's what you get for having an unpredictable API that isn't pretty to begin with.

2 Comments

thanks. but this line if ($.parseJSON(returndata) === false) does not do anything when I pass a json data in.
I just copied that part from your code - my answer is about circumventing the error, not about other problems you may or may not have ;)
-1

may be you need to handle it like this

try{
var response=jQuery.parseJSON('response from server');
if(typeof response =='object')
 {
    //control would reach this point if the data is returned as json
 }
 else
 {
    //control would reach this point if data is plain text  
     if(response ===false)
     {
         //the response was a string "false", parseJSON will convert it to boolean false
     }
     else
     {
          //the response was something else
     }
 }
}
catch(exp){
    //controls reaches here, if the data is html
}

Since you need to check the html data as well, you may need to take care of this,

Might also need to use a try / catch for exceptions if it is possible that parseJSON is going to be dealing with something other than JSON values (i.e. HTML)

REF:How can I check if a value is a json object?

EDIT:Edited to make code more precise towards solution

3 Comments

Won't work, his whole core problem is that parseJSON throws an error, so most of your code is 'unreachable' in the problem case.
@NielsKeurentjes: thats the reason i added a message(in italic font) saying that the parseJSON need to be enclosed within try catch block to handle the exception in case html data is returned .
@NielsKeurentjes: I have edited the answer, i guess now its fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.