Uncaught TypeError: Cannot read property 'name' of undefined
On this line:
if(response.location !== 'undefined')
...you're checking if response.location
is not the string "undefined"
. Since undefined
is not the string "undefined"
, the condition is true. Then you try to use response.location.name
and as response.location
is undefined
, you get the error.
You probably meant either:
if(response.location)
or
if(typeof response.location !== 'undefined')
Ido
Updated on March 10, 2020Comments
-
Ido about 4 years
I tried to fetch data using facebook api into form inputs. Now, everything went just fine until I tried to also fetch the location of the current user.
If the current user have shared his location (Where he is living), then I get no problems. However, if the user hasn't shared his location on facebook, I am getting an error:
Uncaught TypeError: Cannot read property 'name' of undefined
Here is the code I've been using. If you have any idea how to solve it, please comment here :)
<div id="fb-root"></div> <script> // Additional JS functions here window.fbAsyncInit = function() { FB.init({ appId : '*******', // App ID status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); FB.getLoginStatus(function(response) { if (response.status === 'connected') { FB.api('/me', function(response) { document.getElementById("user_login").value="FB - " + response.username; document.getElementById("user_email").value=response.email; document.getElementById("first_name").value=response.first_name; document.getElementById("last_name").value=response.last_name; document.getElementById("user_url").value=response.link; document.getElementById("fbid").value=response.id; if(response.location !== 'undefined') { document.getElementById("location").value=response.location.name; alert(response.location.name); } document.getElementById("registerform").submit(); }); } else if (response.status === 'not_authorized') { alert('error'); } else { alert('Please Log In!'); } }); }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); </script>
-
T.J. Crowder about 11 years@IdoDoron: No worries, glad that helped! Easy mistake to make.