1. Skip to Navigation
  2. Skip to Content
our blog

Submitting a Contact Form via AJAX From Your Facebook Page

Note: this post over over 2 years old and may need modifications.

We 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:

<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" onclick="return 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:

<?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:

?View Code JAVASCRIPT
<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.

29 Responses to Submitting a Contact Form via AJAX From Your Facebook Page

  1. efoc says:

    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?

    • George Huger says:

      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

  2. John says:

    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.’);
    }
    }
    //–>

    • George Huger says:

      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

  3. John says:

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

  4. Mark says:

    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

  5. Mark says:

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

  6. Brandon says:

    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;

  7. Brandon says:

    I’ve got it, thanks!

  8. George Huger says:

    @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.

  9. Reinhard says:

    Hi, i tried your example above. Not working at all in my fanpage.

  10. Robert Garrow says:

    George,
    I used your example to create a form within a Facebook App I use for testing and it worked fine when the action statement and the ajax.post statement pointed to a non-Facebook App. When I pointed it at a Facebook App, the action taken was to go back to my test script as if AJAX would not recognize a url pointing to a Facebook App.
    QUESTION #1: When using the AJAX form as you describe, does the FB AJAX server only allow calls to non-Facebook Apps???
    QUESTION #2: Is there some special code that needs to be added to your example to make it work when pointing at a Facebook App???
    NOTE: Sample code is provided below…
    NON-WORKING EXAMPLE: When I change the action and the ajax.post in the script below to “http://apps.facebook.com/urindexshare/” which is the valid Canvas URL which calls my test script TEST/TESTL.php, the bad behavior mentioned above occurs. The sample shown below, however, works fine.
    WORKING CODE SAMPLE:
    <?php
    $Name=$_POST['name'] ;
    $Email=$_POST['email'] ;
    echo "NAME :"."$Name"."” ;
    echo “EMAIL :”.”$Email”.”” ;

    log_submission($Name, $Email) ;
    echo “ECHO LOG” ;

    global $Name, $Email ;

    function log_submission ($Name, $Email)
    {
    global $Name, $Email ;
    echo “LOG SUBMISSION CALLED :”.”” ;
    }
    ?>

    Name:

    Email:

    Submit

  11. Robert Garrow says:

    George…can’t avoid the truncation for some reason. Too late to fix. Please try to answer my question wihout the code sample.

  12. udhaya says:

    hello,
    in ajax.post method the double slashes in the url http:// comments the following link..

    so when getting value using document.getElementById, actually the ids are encoded by fbml right? i cant get work…

  13. Keith says:

    Great guide… I’ve almost got it working I think.

    My submission just jumps straight to my php page on my server… nothing comes about from Ajax.

    Where should the script be placed in the FBML?

    Thanks!

  14. Dave W. says:

    Hi George
    I am having a couple of issues with the script:

    1) For some reason, whatever input is being accepted by the form is not being submitted through to the processing php file. If I set a default value to the input elements, they do get passed through and submitted, but whatever the user inputs to the form does not get submitted.

    2) Every time the form is submitted, three e-mails are being sent. Can you think of any reason why this might be?

    Any help would be appreciated.

  15. Anz says:

    Excellent!!
    I got form submission working perfectly and the response is showing.. only issue I have is the wait message.. its not getting displayed..

    I copied and pasted the whole code from you as it is.. so the wait line is

    document.getElementById(‘ajaxMessage’).setInnerXHTML(‘Submitting your information, please wait…’);

    Thanks again,
    Anz

  16. Nate says:

    Hi there George, I too am having issues getting any of the Ajax to work (its submitting tho which is a great start for me)

    code is as follows.

    </code

    The html

    Name:

    Email:

    Submit

    Sending your entry

    The submit php

    Am sure you are busy but wondered if I was doing anything stupid?

    Thanks for the tutorial!

    Nate

  17. Nate says:

    Oops < code . doesnt work the way I expected!

    Script

    ######################

    ######################

    Form

    Name:

    Email:

    Submit

    Sending your entry

    ######################

    form_submit.php

    ######################

    If you have time to scan I’d be well happy, if not no worries.

    Feel free to delete that daft post above!

  18. Nate says:

    AH BUM!

    never worry! My bad.

  19. Ash Blue says:

    Thank God, I’ve been looking for a straight and simple answer on this for months. Thank you so much guys.

  20. Jakub says:

    Hi! Don`t you know what is wrong with my code? I still can`t get ajax submission to work :( after submitting the form browser transfers me to webpage…
    – for this example I have deleted the url…

    btw: your form_submit.php doesn`t work:
    Parse error: syntax error, unexpected ‘,’, expecting ‘]’ in /home/public_html/form_submit.php on line 2

    ============================================

    Name:

    City:

    Email:

    Message:

    Submit

  21. Jakub says:

    hmm it didn`t show the code so here it is:

    http://www.ndive.cz/code.doc

  22. Michaleen says:

    http://www.facebook.com/pages/MicroArts-Development/113528355326941?v=app_4949752878
    Trying to get this to work – but I’m banging my head. I don’t see the ‘submitting your information’ message.

    Is there a way to NOT have the page re-direct to my site? I’d like to keep it on the Facebook page.

  23. Ash Blue says:

    Can’t get this to work, doesn’t even hit the return false when I comment out other code.

  24. Fred Black says:

    George;
    Like some of the comments, I could not get this to work. Looking at comment #2’s link, which does work, I was able to figure out what’s wrong.

    On the facebook page, your example uses a submit button on the form with the onsubmit event calling the JavaScript ajax function. But this never calls the ajax JavaScript function. The working page from comment #2 uses the onclick event which does seem to call the JavaScript ajax function. It also uses a regular input with type set to submit vs. a button object, this would probably work either way as long as the onclick even is used vs. the onsubmit event.

    The other thing I found is that, as noted in comment #10, you need the setInnerFBML function in the ajax.ondone event and the setInnerXHTML function when updated the info for the user… BUT – I kept getting a JavaScript error using the single quotes (‘) with setinnerXHTML as you have in your example – I changed them to double quotes (“) and the errors went away.

    These two changes make it work – at least for me.

    Thanks for this information.
    Fred

  25. George Huger says:

    Thank you Fred, that’s great info. I’m going to update the code in this article to note your changes.

    Each case has been different, so if you’ve tried the suggestions listed in the comments and are still having trouble, drop me a line at george [at] illuminatikarate.com and I’ll be happy to take a look. Make sure to attach your code as a text file.

    @ash – drop me an email and we’ll get it worked out.

  26. Ze says:

    In php code missing ] for name.

  27. Pingback: Facebook Contact Forms with AJAX and PHP | Gregory A McMullen

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>