Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Uncaught TypeError: Cannot read property 'replace' of undefined

Anyone can tell me why i am getting this error:

Uncaught TypeError: Cannot read property 'replace' of undefined

function checkNewPost(x) {
        var pid = $('#NewPostbody').attr('class');
        if(pid === 'post-t') {
            setTimeout(checkNewPost, <?php echo $p_id; ?>);
        } else {
            $.ajax({
                type: "POST",
                url: "/html_postReply.php",
                data: "pid="+pid.replace('post-t', '')+"&type=1", 
                success: function(html) {
                    if(html) {
                        $('.tekin').append(html);
                        jQuery("span.timeago").timeago();
                        $(".tekin").scrollTop($(".tekin")[0].scrollHeight);
                    }
                    if(!x) {
                        setTimeout(checkNewPost, <?php echo $p_id; ?>);
                    }
               }
            });
        }
    }
    checkNewPost();
like image 566
innovation Avatar asked Aug 26 '15 16:08

innovation


People also ask

How do you fix undefined properties Cannot be read?

To fix the “cannot read property of undefined” error, use the optional chaining operator on the variable before accessing a property. If the variable is undefined or null , the operator will return undefined immediately and prevent the property access.

How do you replace an undefined empty string?

To replace undefined with a empty string with JavaScript, we can use the || operator to return a default if its left operand is undefined .


1 Answers

I believe that this error is caused by one of two scenarios, based on the given information above:

  1. $('#NewPostBody) is not being found in the DOM

  2. $('#NewPostBody) is being found but has no class attribute.

This can be solved using the following method:

var pid = ($('#NewPostBody').length && $('#NewPostBody').attr('class')) 
    ? $('#NewPostBody').attr('class') 
    : "";

The ternary operator along with truthy/falsy logic should result in either the class being returned or an empty string. Either way, pid.replace('post-t', '') can safely be called without resulting in an error.

like image 86
War10ck Avatar answered Sep 28 '22 16:09

War10ck