Pre-populate Forms for Advanced Targeting

A popular feature of online forms is the ability to personalize the form for each visitor. You can add known information to some form fields to make it easier to complete and reduce the likelihood of errors. You can even add data to hidden fields to track and target certain demographics and behaviors. Our Pre-populate function makes it possible by adding variable text to the URL that tells the form where and what to insert.

An overview of pre-populating can be found in a previous article which outlines the basic usage. An example of a pre-populate link is:

What if you wanted to do the same thing with an embedded form? What about changing the value dynamically using Javascript or PHP?

Pre-populating Embedded Forms

Embedding forms is a simple matter of pasting the form’s embed code into your page code where you want the form to appear. As shown on the documentation page, the embed code has a prePopulate parameter where you can list values to automatically enter when the form is loaded. It looks like this:

prePopulate: { "2":"Alex", "3":"Powers","4-1":"1","4-2":"2"},

This line will add ‘Alex’ to the 2nd item, ‘Powers’ to the 3rd item, etc. Here’s where it gets interesting.

Dynamically Changing

Say you have a form to collect information after your visitors are logged in. Your site will already have some identifying information so you don’t need to ask for it again on your embedded form. You can write that information directly into your embed code as the page loads.

PHP: Depending on your content management system or platform, your user information is accessed through a global variable. Using WordPress as an example, your code would look like this:

<?php
$current_user = wp_get_current_user();
?>

prePopulate: { "2":"<?php echo $current_user->user_email ?>"},

Javascript: Many times you can’t access the server-side code (PHP, Java, etc.) but you can still get user information using client-side tools like Javascript or jQuery. Let’s say your page renders with the account username in the header within an element with the id of “username”:

prePopulate: {"2":document.getElementById('username').innerHTML},

jQuery: If your site uses jQuery it’s even easier:

prePopulate: {"5":$('#username').text()},

Get the Referrer

Here’s a trick that you can use to document where your visitors came from. Say you have a contest entry and you have lots of sites that send traffic your way. This will allow you to add the referring site to a hidden field in your form that you can tally at the end of your campaign to see who sent the most traffic.

prePopulate: {"1":document.referrer},

If the first item in your form is a Hidden Field item, this code will put the referring site into the value of that item as the page loads.

If you have any questions or any other tips for using prePopulate, let us know in the comments.