My previous article explained how to get started with Facebook API development using PHP. This article goes a step further by exploring how to create more advanced Facebook applications using the Facebook JavaScript (FBJS) framework. FBJS allows you to use JavaScript within your Facebook applications, opening the door for more interactive, Ajax-driven user controls.
The FBJS framework is written in a way that also allows you to use Facebook's built-in resources (such as dialog boxes, confirmation popups, and so on) easily, but it has with few limitations as well. For example, you cannot use the onload function with FBJS and it does not allow you to access too many DOM properties at the window level. But not to worry, the example in this article does not require those functions anyway.

Your First FBJS Application

So let's get started with our first FBJS application. We are going to create a simple contact/feedback form, which you can then insert on your Facebook page to let users leave feedback or contact you right away.
I presume that you have already completed your application setup process. If you have not registered your application yet, please refer to my previous article on building your first Facebook app with PHP for instructions.
To start building the application, create a simple HTML form as shown below.
<form action="" id="ContactForm" name="ContactForm" method="post">
  <p>
    Name: <input type="text" tabindex="1" value="" name="name" id="name" />
  </p>
  <p>
    Address:  <input type="text" tabindex="2" value="" name="address" id="address" />
  </p>
  <p>
    Phone: <input type="text" tabindex="3" value="" name="phone" id="phone" />
  </p>
  <input type="button" class="submit" onclick="contact();" value="Send Feedback / Contact"/>
</form>
As you can see, this simple HTML form calls the JavaScript (JS) function contact(); on submit. This function will now use FBJS to make an Ajax request back to your server and do the required set of actions. So, write the JS function to learn more about it.
<script>
function contact()
  {
    var ajax = new Ajax();
    ajax.responseType = Ajax.RAW;
    ajax.ondone = function(data)
    {
      var msgdialog = new Dialog();
      msgdialog.showMessage('Confirmation',data);
msgdialog.onconfirm = function() { document.setLocation('http://www.facebook.com/digimantra?v=wall'); };
      return false;
    }
    ajax.onerror = function() {
      var msgdialog = new Dialog();
      msgdialog.showMessage('Error', 'An error has occurred while trying to submit.');
      return false;
    }
    var queryParams = {
      'name' : document.getElementById('name').getValue(),
      'address' : document.getElementById('address').getValue(),
      'phone' : document.getElementById('phone').getValue()
    };
    ajax.post('http://your_app_url.com/submit.php?sys=fbpage', queryParams);
  }
</script>
This self-explanatory JavaScript code is very easy to understand. You create the Ajax object using the new Ajax(); method and then set its return type. In this example, we keep the return type as RAW, but you can choose JSON or FBML as well. You also can embed HTML and JavaScript code in the same file; in this example, we call the file form.php and it submits data to submit.php (see the full code listing below).
Next, we post our data from the form to a PHP file where the data is processed and the corresponding response is returned. We use ajax.post() to post the data on the given URL. The data is easily collected using the native JS function getElementById and is passed in the form of comma-separated key/value pairs.
If the Ajax call is successful, then the function ondone is triggered. Otherwise, the onerror function is triggered so that your script can act accordingly. In this example, we show a confirmation dialog using Facebook's dialog utility and then redirect the user to any other link, if needed.

Behind the Scenes of the FBJS Application

Now, what happens behind the scenes in our PHP file is interesting. Our PHP script should be able to recognize legit requests and reject any invalid or fake requests made to the script. Notice that Facebook always sends some session data with every GET or POST request. So, to see if the request is valid, we write the login on top of our PHP file. These values are prefixed with fb_sig_.
Among these values, we will get one "Signature Value" $_POST['fb_sig'], which we should verify at our end to check the authenticity of the request made. To verify the signature, you need to follow the following steps.
  1. Remove the fb_sig_ prefix from all of the keys.
  2. Sort the array alphabetically by key.
  3. Concatenate all key/value pairs together in the format "k=v" (omitting the signature itself, because that is what we are calculating).
  4. Append your secret key, which you can find by going to the Facebook developers page and following the link for your application.
  5. Take the md5 hash of the whole string.
In the following code snippet (store it in submit.php for this example), this Facebook signature is verified. On verification, we send the contact information filled out by the user to the administrator's email address. If it fails, we display an error message. Visit Facebook's WiKi page for more information on its signature verification methodology.
<?php
$fbsig = array();
$appsecret = YOUR_SECRET_APP_KEY;

foreach($_POST as $key=>$value)
{
  if(substr($key,0,7) == 'fb_sig_')
  {
    $fbsig[substr($key,7)] = $value;
  }
}
ksort($fbsig); 
foreach($fbsig as $key=>$value)
{
  $string .= $key . '=' . $value;
}
$string.= $appsecret;
//verify this string with the signature value.
if(md5($string) != $_POST['fb_sig'])
{
//send an error message and exit
  echo 'Invalid request !! Are you logged in?';
  die;
}
extract($_POST);
$msg = "Name :  $name \n";
$msg .= "Address : $address \n";
$msg .= "Phone: $phone \n";
//send a mail of the information or store in database
mail('your_email_addr@gmail.com','contact',$msg);
//send a confirmation message which is displayed to the user.
echo "Thank You, for your interest in Digimantra."
?> 

What Have You Learned?

With the power of Ajax built into FBJS, you can create more interactive Facebook applications. The example that we just ran through was a simple demonstration of how doing to develop an application easily with FBJS. As you learn more about it, you can create more powerful applications that allow you to utilize Facebook's built-in resources, such as friend picker and chat.
Sachin Khosla is a Web developer and technology evangelist who has written and spoken extensively about open source technology. Sachin is part of an active open source community that organizes OSScamp in Delhi, India. To learn more about this author, read Sachin's blog at Digimantra.com.