Uncaught TypeError: Cannot read the 'name' property from undefined

I tried to get data using facebook api in form inputs. Now everything went fine until I tried to find the location of the current user.

If the current user has shared his location (where he lives), then I have no problem. However, if the user has not shared their location on facebook, I get an error: Uncaught TypeError: Cannot read property 'name' of undefined

Here is the code I used. If you have ideas on 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> 
+7
source share
1 answer

In this line:

 if(response.location !== 'undefined') 

... you are checking if response.location string "undefined" . Since undefined not an undefined string, the condition is true. Then you try to use response.location.name and as response.location is undefined , you get an error.

You probably meant:

 if(response.location) 

or

 if(typeof response.location !== 'undefined') 
+16
source

All Articles