jQuery length of object to determine existence gives error?
if (pid.length)


causes a reference error in your script if pid is undefined.  So, if you don't know that pid exists ahead of time, then you have to check to see if that object is valid before trying to reference properties on it.

FYI, you could probably just use:

if (pid)


because that would protect you from pid being undefined or an empty string.



It has been raised in comments that maybe you're actually just trying to test for the existence of a DOM object, not the attribute.  If that's the case, then you should just be doing this:

if ($('input[name="product_id"]').length)


which tells you if the selector matched any DOM objects.