0

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?

1 Answer 1

3

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){
    //...
}
Sign up to request clarification or add additional context in comments.

1 Comment

That was the problem... being empty! Thx alot!

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.