Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Project "Facebook Javascript SDK"
    Purpose
Download the full source code for this example

The purpose of this page (current to the specifications of Facebook SDK usage as of June 2012) is to show you how to get Facebook user profile information from Facebook so that you can put that information into a form on your website (so your visitor does not have to type in a bunch of information).


NOTE: This page assumes you are familar with creating and configuring an "App" in Facebook which is a requirement; if you are not please see the introduction.

Something Worth Mentioning with Your "App"
Once you've created an "App" in Facebook, be sure to match the domain name to the actual domain name that your webpage (with the form and Javascript SDK code) will be at. Please see the illustration below of what needs to be examined in your "App" settings at Facebook.


(Enlarge)
  1. Ensure the domain name is entered as it will be used.


Mechanics of Getting Facebook User Info Into Your Webpage Form
From examining the code below (which you can also download from the link provided above), you can see that the following conditions influence how and when you are able to get Facebook user profile data into the form on your webpage:
  1. If a Facebook user is logged out of Facebook and accesses your webpage, he/she will need to click on the Facebook button "Login" to log into Facebook.
  2. If you are requesting Facebook user profile data which requires some type of permission to access (see this page for a list) then, after the visitor logs into Facebook (see this image), they will be prompted to approve that your "App" can access the permissioned data (see this image). If you do not request permissioned data, then the user would not get a prompt to approve the retrieval of data.
  3. After the visitor has approved your "App" (your webpage with the Javascript SDK and your "appID") if the visitor re-visits your webpage in the future then his/her Facebook user profile data will already be available and automatically put into the form. That is, the visitor does not have to "re-approve" your "App" once they have approved it once.
  4. At this point the SDK will retrieve the applicable Facebook user profile data from Facebook so that it can be placed into your form.
A Few Bonuses
Since it can be a challenge to "see" what is being returned by Facebook from the Javascript SDK, I've included a few javascript functions in the example code you can download which show (1) filtering out whitespace and line breaks, (2) seeing the JSON structure of the returned data as a javascript alert to make referencing things easier.

Code Snippet For Cleaning Whitespace/Line Breaks
function wSpaceFilter(data) {
	/* Remove leading, trailing whitespace, more than one whitespace and line breaks within the string */
	data = data.replace(/(^\s*)|(\s*$)/gi, "").replace(/\s{2,}/gi, " ").replace(/(\r\n|\n|\r)/gm, " ");
	return(data);
}


Code Snippet For Viewing JSON data in a Javascript Alert Box
function rawData(dataObject) {
	/* Quick testing, show what is available for access */
	var data = '';
	for (var pair in dataObject) {
		if (typeof dataObject[pair] === 'object') { data = data + pair + ' ->' + '\n'; }
		else { data = data + pair + ' : ' + dataObject[pair] + '\n'; }
		try {
		     var sDataObject = dataObject[pair];
		     if (typeof sDataObject === 'object') {
			for (var sPair in sDataObject) {
				if (typeof sDataObject[sPair] === 'object') { data = data + '    ' + sPair + ' -->' + '\n'; }
				else { data = data + '    ' + sPair + ' : ' + sDataObject[sPair] + '\n'; }
				var cDataObject = sDataObject[sPair];
				if (typeof cDataObject === 'object') {
					for (var cPair in cDataObject) {
						if (typeof cDataObject[cPair] === 'object') { data = data + '        ' + cPair + ' --->' + '\n'; }
						else { data = data + '        ' + cPair + ' : ' + cDataObject[cPair] + '\n'; }
							var nDataObject = cDataObject[cPair];
							if (typeof nDataObject === 'object') {
								for (nPair in nDataObject) {
									if (typeof nDataObject[nPair] === 'object') { data = data + '            ' + nPair + ' ---->' + '\n'; }
									else { data = data + '            ' + nPair + ' : ' + nDataObject[nPair] + '\n'; }
								}
							} } } } } } catch(error_sPair) { /* Show error if needed */ } }
	return(data);
}


The Full Example
The code below (Download the full source code for this example) show exactly how to retrieve Facebook user profile information from Facebook and place that information into a form on your webpage. Don't forget, if you are not going to be requesting permissioned data, then you do not need to include values in the Facebook button "fb:login-button" and you don't need to specify them in "scope" of the Javascript SDK functions "FB.Event.subscribe", and, "FB.getLoginStatus". Check it out:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>FB SDK Demonstration</title>
<style type="text/css">
body, td, form {
		padding: 2px 2px 2px 2px;
		margin: 0px 0px 0px 0px;
		font-family: verdana;
		font-size: 9pt;
		color: #000000;
	       }
.altTD {
	background-color: #e2ebfe;
       }
.txtBox {
	 font-family: verdana;
	 font-size: 9pt;
	 color: #ae7805;
	 background-color: #fdf0d5;
	 border-style: solid;
	 border-width: 1px;
	 border-color: #ae7805;
	 width: 250px;
	}
</style>
</head>
<body>
<b>Simulated Form:</b><br /><br />

<!-- Start FB SDK Work -->
<div id="fb-root"></div>
<fb:login-button autologoutlink='true' perms='email,user_birthday,user_location,user_education_history,user_website'></fb:login-button>
<script>
	window.fbAsyncInit = function() {
			/* Initialize FB */
			FB.init({
				appId      : '11111111111111',					/* App ID of the App registered in FB - https://developers.facebook.com/apps/ */
				channelUrl : '//www.yoursite.com/fbsdk-channel.aspx',		/* Channel File - required to resolve potential cross-domain communication between this domain and FB */
				status     : true,						/* Check login status of the user accessing the webpage this code is on */
				cookie     : true,						/* Enable cookies to allow the server to access the session */
				xfbml      : true,						/* Parse XFBML tags present within the webpage such as "fb:login-button" */
				oauth	   : true						/* oAuth is required now */
			});
			/* Capture Events */
			var tmp_userID = '', tmp_signedRequest = '', tmp_expiresIn = '', tmp_accessToken = '';
			FB.Event.subscribe('auth.login', function(response) {
				/*
				  Log the user in with the button click "fb:login-button" on your webpage when FB detects they are not logged into FB already OR the user has not authorized (or "authenticated") the "App" (your webpage)
				  Request permissions to access email, etc which are not available by default - http://developers.facebook.com/docs/reference/api/user/
				*/
				if (response.authResponse) { userLoggedIn(); }
			}, {scope: 'email,user_birthday,user_location,user_education_history,user_website'});
			FB.Event.subscribe('auth.logout', function(response) {
				/* Some action to perform when the user logs out via the "fb:login-button" displaying "Facebook Logout" on your webpage */
				userLoggedOut();
			});
			FB.getLoginStatus(function(response) {
				/* This is executed on load of the "App" (your webpage) in the event the user has already logged into FB */
				if (response.status === 'not_authorized') {
					/* The user has already logged into FB but not authorized the "App" (your webpage) */
				}
				else if (response.status === 'connected') {
					/* The user has logged into FB and authorized the "App" (your webpage) to get their user information */
					tmp_userID = response.authResponse.userID;
					tmp_signedRequest = response.authResponse.signedRequest;
					tmp_expiresIn = response.authResponse.expiresIn;
					tmp_accessToken = response.authResponse.accessToken;
					processUserInformation();
				}
				else { /* The user has not yet logged into FB */ }
			}, {scope: 'email,user_birthday,user_location,user_education_history,user_website'});

			/* Handle Events */
			function userLoggedIn() {
				/* Triggered after user successfully logs into Facebook with their account from the "App" (your webpage) */
				/* Forward to "processUserInformation()" unless something unique needs to be done */
				processUserInformation();
			}
			function userLoggedOut() {
				/* User has initiated a logout from Facebook using the "fb:login-button" button from the "App" (your webpage) */
			}
			function processUserInformation() {
				/* Get the user's information to put into the webpage since the user is logged into FB and authorized the "App" (your webpage) */
				FB.api('/me', function(response) {
					/*
					  Put the data into the form in the webpage
					  NOTES: Although "user_birthday" is requested, the returned field is just "birthday" with a value like "09/23/1993"
						 Although "user_location" is requested, the returned scope is the object "location" with fields "name" and "id"; "name" would have a value like "Boggs, California"
					*/
					//alert(rawData(response)); /* Uncomment in order to see what data is available for the "App" (your webpage) to access */
					document.getElementById('First_Name').value = wSpaceFilter(response.first_name);
					document.getElementById('Last_Name').value = wSpaceFilter(response.last_name);
					document.getElementById('Gender').value = response.gender;
					if (response.email) { document.getElementById('User_Email').value = response.email; }
					if (response.birthday) { document.getElementById('Birthday').value = response.birthday; }
					if (response.website) { document.getElementById('Website').value = wSpaceFilter(response.website); }
					var userCity = '', userState = '';
					if (response.location) {
						if (response.location.name.indexOf(',') > -1) { userCity = wSpaceFilter(response.location.name.split(',')[0]); userState = wSpaceFilter(response.location.name.split(',')[1]); }
						else { userCity = wSpaceFilter(response.location.name); }
					}
					document.getElementById('City').value = userCity;
					document.getElementById('State').value = userState;
					/* Pull high school name and education */
					var high_school_grad_year = '', high_school_name = '';
					if (response.education) {
						if (typeof response.education === 'object') {
							var eDataObject = response.education;
							for (var ePair in eDataObject) {
								if (typeof eDataObject[ePair] === 'object') {
									var tDataObject = eDataObject[ePair];
									var tmp_hsYear = '', tmp_hsName = '';
									for (var tPair in tDataObject) {
										var tnDataObject = tDataObject[tPair];
										if (tPair === 'school') {
											for (var hsSchool in tnDataObject) {
												if (hsSchool === 'name') { tmp_hsName = tnDataObject[hsSchool]; }
											}
										}
										else if (tPair === 'year') {
											for (var hsSchoolYr in tnDataObject) {
												if (hsSchoolYr === 'name') { tmp_hsYear = tnDataObject[hsSchoolYr]; }
											}
										}
										else if (tPair === 'type') {
											if (tDataObject[tPair].toLowerCase() == 'high school') {
												high_school_grad_year = tmp_hsYear; high_school_name = tmp_hsName;
											}
										}
									}
								}
							}
						}
					}
					document.getElementById('HsName').value = wSpaceFilter(high_school_name);
					document.getElementById('HsYear').value = high_school_grad_year;
				});
			}
			function wSpaceFilter(data) {
				/* Remove leading, trailing whitespace, more than one whitespace and line breaks within the string */
				data = data.replace(/(^\s*)|(\s*$)/gi, "").replace(/\s{2,}/gi, " ").replace(/(\r\n|\n|\r)/gm, " ");
				return(data);
			}
			function rawData(dataObject) {
				/* Quick testing, show what is available for access */
				var data = '';
				for (var pair in dataObject) {
					if (typeof dataObject[pair] === 'object') { data = data + pair + ' ->' + '\n'; }
					else { data = data + pair + ' : ' + dataObject[pair] + '\n'; }
					try {
					     var sDataObject = dataObject[pair];
					     if (typeof sDataObject === 'object') {
						for (var sPair in sDataObject) {
							if (typeof sDataObject[sPair] === 'object') { data = data + '    ' + sPair + ' -->' + '\n'; }
							else { data = data + '    ' + sPair + ' : ' + sDataObject[sPair] + '\n'; }
							var cDataObject = sDataObject[sPair];
							if (typeof cDataObject === 'object') {
								for (var cPair in cDataObject) {
									if (typeof cDataObject[cPair] === 'object') { data = data + '        ' + cPair + ' --->' + '\n'; }
									else { data = data + '        ' + cPair + ' : ' + cDataObject[cPair] + '\n'; }
										var nDataObject = cDataObject[cPair];
										if (typeof nDataObject === 'object') {
											for (nPair in nDataObject) {
												if (typeof nDataObject[nPair] === 'object') { data = data + '            ' + nPair + ' ---->' + '\n'; }
												else { data = data + '            ' + nPair + ' : ' + nDataObject[nPair] + '\n'; }
											}
										}
									}
								}
							}
						}
					}
					catch(error_sPair) { /* Show error if needed */ }
				}
				return(data);
			}
		};

		/* 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>
<!-- End FB SDK Work -->

<!-- Start Example Form -->
<form method="post" action="" />
	<table border="0" cellpadding="0" cellspacing="0" width="500px"><tr>
		<td width="30%" valign="center"><center>Personal Website(s)</center></td>
		<td width="70%" valign="center"><center><input type="text" name="Website" id="Website" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center" class="altTD"><center>First Name</center></td>
		<td valign="center" class="altTD"><center><input type="text" name="First_Name" id="First_Name" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center"><center>Last Name</center></td>
		<td valign="center"><center><input type="text" name="Last_Name" id="Last_Name" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center" class="altTD"><center>Email</center></td>
		<td valign="center" class="altTD"><center><input type="text" name="User_Email" id="User_Email" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center"><center>Gender</center></td>
		<td valign="center"><center><input type="text" name="Gender" id="Gender" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center" class="altTD"><center>Birthday</center></td>
		<td valign="center" class="altTD"><center><input type="text" name="Birthday" id="Birthday" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center"><center>City</center></td>
		<td valign="center"><center><input type="text" name="City" id="City" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center" class="altTD"><center>State</center></td>
		<td valign="center" class="altTD"><center><input type="text" name="State" id="State" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center"><center>HS School Name</center></td>
		<td valign="center"><center><input type="text" name="HsName" id="HsName" class="txtBox" value="" /></center></td>
	</tr><tr>
		<td valign="center" class="altTD"><center>HS "Graduation" Year</center></td>
		<td valign="center" class="altTD"><center><input type="text" name="HsYear" id="HsYear" class="txtBox" value="" /></center></td>
	</tr><tr>
	</tr></table>
</form>
<!-- End Example Form -->

</body>
</html>


About Joe
Find Out Now!