Submitting a Contact Form via AJAX From Your Facebook Page

Posted December 3rd, 2009 by George Huger

FacebookWe recently created a contact submission form on a client’s Facebook page, and were not satisfied with the default user experience. For starters, the form opened a new window, and there was no way to redirect the user back to a confirmation message on the Facebook page.

We decided to submit the form via AJAX instead, and show the confirmation message directly on the Facebook page. This way the user would not have to leave the Facebook page, resulting in a smoother user experience. We couldn’t find a good explanation of how to do this on Google, so after figuring it out I decided to go ahead and write it up.

The following example will show you how to submit a basic contact form using AJAX from within your Facebook page. All HTML and Javascript that follows should be pasted directly into the “Edit FBML” screen on Facebook.

Here’s the example form HTML we’ll use for the rest of this article. It’s just two text fields (name and email) and a submit button:

1
2
3
4
5
6
7
8
9
10
11
12
<form action="http://mywebsite.com/form_submit.php" method="post">
     <p>
          <label for="name">Name:</label>
          <input type="text" name="name" id="name" />
     </p>
     <p>
          <label for="email">Email:</label>
          <input type="text" name="email" id="email" />
     </p>
     <button type="submit" onsubmit="submitAjaxForm()">Submit</button>
     <p id="ajaxMessage"></p>
</form>

There’s three things you should take note of:

  1. The form’s action attribute is set to a page on mywebsite.com, not facebook.com (replace mywebsite.com with your own domain)
  2. The submit button has an onSubmit event that calls a function submitAjaxForm, which we’ll define shortly
  3. At the end of the form is an empty paragraph tag. We’ll use this space to display messages to the user.

On our server, form_submit.php is a simple PHP script that logs the submissions, and sends back a message for the user letting them know the submission was successful. It might look something like this:

1
2
3
4
<?php
     log_submission($_POST['name', $_POST['email']);
     echo "Thank you for your submission!";
?>

Of course, your script will be more sophisticated than this one, and doesn’t have to be written in PHP. Its on your server, so you can handle logging the submission however you like. Just make sure the output is valid FBML.

With the form HTML added to your Facebook page and the logging script in place, the only thing left is adding the Javascript to submit the form via AJAX and show the confirmation message.

Note: Facebook does not allow you to use any Javascript function you like, for security purposes. Instead they’ve created a library of Javascript functions for accessing the DOM, AJAX, and event binding called FBJS. These functions are used in the example below.

We’ll now define the submitAjaxForm() function we referenced earlier in our submit button’s onSubmit event:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script><!--
function submitAjaxForm() 
{ 
	// declare a new FBJS AJAX object
	var ajax = new Ajax(); 
	ajax.responseType = Ajax.FBML;
 
	// define a callback to handle the response from the server
	ajax.ondone = function(data) 
	{ 
		document.getElementById('ajaxMessage').setInnerFBML(data);
	}
 
	// let the user know we're sending the data	
	document.getElementById('ajaxMessage').setInnerXHTML('Submitting your information, please wait...');
 
	// collect field values
	var queryParams = { 'name' : document.getElementById('name').getValue(), 'email' : document.getElementById('email').getValue() };
	ajax.post('http://mywebsite.com/form_submit.php', queryParams);
	return false;
}
//--></script>

Note: The opening and closing HTML comments embedded in the Javascript are important, so leave them intact.

The example is fairly self explanatory, but here’s what’s happening:

  1. Declare a new Ajax object, which is one of the FBJS classes. We then set its response type to FBML (Ajax.RAW and Ajax.JSON are also accepted).
  2. Define a callback function to handle the response from the server. In this case, our function simply takes the response from the server and displays it in the #ajaxMessage paragraph we defined earlier.
  3. Update the user to let them know their data is being submitted using FBJS’s setInnerFBML function.
  4. Collect the form field’s values into an array named queryParams, using FBJS’s getElementById and getValue functions. Although getElementById is similar to the standard Javascript function, it accounts for the random slugs Facebook injects into div id’s for security (View Source on a Facebook page and look at the div ID’s to see this in action).
  5. Send the AJAX request, using FBJS’ Ajax.post function. The second argument is optional, and should be an array containing the query parameters.
  6. “return false;” prevents the form’s normal submit behavior

That’s all there is to it! If you have any questions or if I should clarify a section, let me know in the comments.

Get a Trackback link

10 Comments

  1. efoc, December 20, 2009:

    I try this but message “Submitting your information, please wait…” is not showing up. Is this after form submitted, pages will redirect to my website?

  2. John, January 19, 2010:

    I can’t for the life of me get ajax to work on a page I’m creating. Here is the page:

    http://www.facebook.com/pages/CleanStart-Law-Firm/395588170477

    Here is the code. Is there something missing here? I use jQuery constantly but this is my first attempt with FBJS. Your help is appreciated!

    Your Name:

    Email address:

    Phone Number:

    Your Message:

    <!–
    function submitAJAXform()
    {
    document.getElementById('ajaxResponse').setInnerFBML('Submitting your information, please wait…’);
    var ajax = new Ajax();
    ajax.responseType = Ajax.FBML;
    ajax.requireLogin=false;
    var queryParams = {
    ‘name’ : document.getElementById(‘username’).getValue(),
    ‘email’ : document.getElementById(‘email’).getValue(),
    ‘phone’ : document.getElementById(‘phone’).getValue(),
    ‘details’ : document.getElementById(‘details’).getValue()
    };
    ajax.post(‘http://www.wcassist.com/CleanStart-FB-Contact.php’, queryParams);
    ajax.ondone = function(data)
    {
    document.getElementById(‘ajaxResponse1′).setInnerFBML(data);
    }
    ajax.onerror = function() {
    var msgdialog = new Dialog();
    msgdialog.showMessage(‘Error’, ‘An error has occurred while trying to submit.’);
    }
    }
    //–>

  3. George Huger, January 20, 2010:

    Hi efoc -

    Are you sure you’ve included a paragraph with the id ajaxResponse? If so, the user should see “Submitting your information, please wait…” during the form submission (might be very fast, you could miss it), and “Thank you” afterwards. Since we’re using AJAX the form would not redirect to your site.

    Let me know how it goes, happy to help.

    Cheers,
    George

  4. George Huger, January 20, 2010:

    Hi John,

    I went to the page and submitted a contact inquiry, but it behaved as a normal POST request and showed a confirmation message. Do you have another version I can check which includes the code from this article?

    One thing I noticed is that the code you’re using is copy and pasted from here. That’s totally fine, but I don’t see an element with id ajaxResponse, which is present in my sample code (used to display messages to the user, so they know whats going on). That could be part of the problem.

    The second thing is to make sure you’re calling submitAjaxForm() in the onclick event of your button.

    If you’re not able to get it to work drop me a line, my email is george [at] illuminatikarate.com. Between the two of us I’m sure we can get it working.

    BTW, you’re Facebook fan page looks great. Nice work.

    Cheers,
    George

  5. John, January 21, 2010:

    Hey, thanks George I’ll shoot you an email.

  6. Mark, January 26, 2010:

    Hey George

    I can’t get the AJAX part of the script to work. Currently, it simply loads the form_submit.php page & sends the form… Nothing “ajax-y” is happening…

    Can you confirm where the script tag should be placed? in my FBML page? at the top/bottom? inside a header tag or anything?

    Appreciate the help
    Regards

  7. Mark, January 26, 2010:

    part of the problem is that your button calls the “submitAjaxForm” function, but the function you’ve written is “submitBetaForm”

  8. Brandon, January 27, 2010:

    Hi John

    Is there a reason you can think of for why the form still returns true (goes to the receiving php page) when I try to include drop down values?

    Works fine when I do not include any drop down select values. Here is the query string which goes to the php file even though return false is added:

    var queryParams = { ‘first_name’ : document.getElementById(‘first_name’).getValue(), ‘last_name’ : document.getElementById(‘last_name’).getValue(), ‘email’ : document.getElementById(‘email’).getValue(), ‘postcode’ : document.getElementById(‘postcode’).getValue() , ‘dob_day’ : document.getElementById(‘dob_day’).getValue() , ‘dob_month’ : document.getElementById(‘dob_month’).getValue() , ‘dob_year’ : document.getElementById(‘dob_year’).getValue() };
    ajax.post(‘http://www.website.com.au/test.php’, queryParams);
    return false;

  9. Brandon, January 27, 2010:

    I’ve got it, thanks!

  10. George Huger, January 27, 2010:

    @mark – John and I were able to get his working via email. The trick ended up being changing the setInnerFBML() call to setInnerXHTML() on line 16 of the Javascript I posted. Its been changed in the example above.

    If you’re still having trouble, try reducing the complexity of your function by commenting out lines, until you can keep the form from submitting (meaning return false is being hit).

    If you’re still having trouble drop me a line via email: george at this domain.

    Also – thanks for the catch on submitBetaForm() vs submitAjaxForm(). I adapted this code from some production code so it could go on the blog, and I missed that line. Fixed now.

Leave a comment

Give Us A Call: (919) 805-3003