Reputation:
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();
Upvotes: 6
Views: 32005
Reputation: 12508
I believe that this error is caused by one of two scenarios, based on the given information above:
$('#NewPostBody)
is not being found in the DOM
$('#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.
Upvotes: 2