Why is this causing an error?

I have a jquery json ajax call and inside my success function I have the following check:

if(data['error'] === 1) {

    $return_feedback.html(data['error_msg']);

}

      

For some reason I can't figure it out, although right now, I'm getting an error:

'Uncaught TypeError: Cannot read property 'error' of null'

      

And it refers to the line if (data ['error'] above.

So I looked at what my script is returning and it's true - no data. But shouldn't you just skip that if statement? Or should I check if the data value exists before calling the if statement?

Thank you for your time.

+3


source to share


3 answers


data is zero

use this:



if (!data){
    //throw exception or handle the problem
}
else if(data['error'] === 1) {
    $return_feedback.html(data['error_msg']);
}

      

+3


source


Yes, you have to check if the data is true:



if(data && data['error'] === 1) {

    $return_feedback.html(data['error_msg']);

}

      

+3


source


You can use something like this, which should work without error:

if(typeof data!=='undefined' && data['error'] === 1) {

      

+1


source







All Articles