I am manipulating the json array in the jquery.Ajax function. The syntax got me very confused so I am not able to find this error. What I am doing I have bind the click function to the anchor tag and then when I hit that anchor tag and called the foo() function this error showed up UncaughtReferenceError : foo is not defined at HTMLAnchorElement.onclick
function show(thelink)
{
var cat = thelink.innerHTML;
var productContainer = document.getElementById("productContainer");
$.ajax({
type:"POST",
url:"fetchdata1",
data:"cat="+cat,
success:function(data){
productContainer.innerHTML ="";
var $productContainer = $('#productContainer');
$.each(data,function(key,value){
if(value['newVar'] === 1)
{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span>\n\
<br/><br/><a href='#' onclick='foo(this)' pid='"+value['id']+"'>REMOVE</a></div>");
}
else{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span></div>");
}
}) ;
}
});
function foo(obj){
var pid = $(obj).attr("pid");
$(obj).bind("click", function(){
$.ajax({
type:"POST",
url:"removeFromWishlist",
data:"pid="+pid,
success:function(response){
}
});
});
}
return false;
}
Your problem here is that you have defined function foo inside show function, so it will only be accessible from show scope.
So when you use onclick='foo(this)' in your HTML, you are referring a foofunction in the window global scope so that's why you got:
UncaughtReferenceError : foo is not defined at HTMLAnchorElement.onclick
You need to move function foo declaration outside of show function, so it can be accessible from window global scope.