Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this throwing up 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 seem to understand though right now, I'm getting an error:

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

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

So I've looked at what my script is returning and it is true - there is no data. But then shouldn't it just skip this if statement altogether? Or am I supposed to check if the data value exists first before calling an if statement?

Thanks for your time on this.

like image 934
willdanceforfun Avatar asked Dec 13 '25 15:12

willdanceforfun


2 Answers

data is null

use this:

if (!data){
    //throw exception or handle the problem
}
else if(data['error'] === 1) {
    $return_feedback.html(data['error_msg']);
}
like image 188
pylover Avatar answered Dec 16 '25 05:12

pylover


Yes you should check if data is truthy first:

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

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

}
like image 23
Paul Avatar answered Dec 16 '25 04:12

Paul