user2840318
user2840318

Reputation: 1127

jQuery/Json - Cannot convert 'data' to object

I've a simple ajax/json request with jQuery:

$.ajax({
              type: "POST",
              url: "/some-json-url",
              data: "score=" + 1,
              dataType: 'json',
              success: function(data){
                if(data.msg){ 
                    alert(data.msg);
                }
             }
        });

However, if the msg is not set, I gen an error (looking through Opera Dragonfly):

Unhandled Error: Cannot convert 'data' to object

How can I check if it exists or not... in a valid way?

Upvotes: 0

Views: 137

Answers (1)

musefan
musefan

Reputation: 48415

If the problem is with data being null then you can check it like so:

if(data && data.msg){
    //...
}

or if you have multiple properties, either like this:

if(data){
    if(data.msg){
        //...
    }
}

or return early:

if(!data)
    return;

if(data.msg){
    //...
}

Upvotes: 3

Related Questions