Skip to main content
Skip table of contents

Example: Using a public data call to display a supporter’s MP on a data capture action

This example will show you how to use a public data call to query our target databases for information and display them to the user, without having to use an email to target form. This uses the EaAOContactData service.

Here we’ll be using a postcode field on the first page of an action. When the supporter types this in and submits the page, the second page uses the postcode to request information from our MP contact database and then displays the supporter’s MP in a copy block.

  1. Create the first page of the data capture action, including the postcode field and anything else you want.

  2. On the second page, add a Code Block

  3. Inside the code block, put in code like this  (NOTE: Replace ‘your-token’ with your public token):

<p>Your MP is <spanid="mpName"></span></p>

<script>varuserPostcode=encodeURIComponent($.trim($('#userPostcode').text()));var service = "EaAOContactData";varconstituencyDatabaseId = 3;vartoken="your-token";vardataUrl="" + service + 
    "&constituencyDatabaseId=" + constituencyDatabaseId +
    "&postcode="+userPostcode +
    "&token=" +token+"&contentType=json";varnewDataRequest=$.ajax({url:dataUrl,dataType:"jsonp",crossDomain:true,timeout:30000});newDataRequest.done(function(data) {varmpName=data.rows[0].columns[1].value+''+data.rows[0].columns[2].value+''+data.rows[0].columns[3].value+''+data.rows[0].columns[4].value;$('#mpName').text(mpName);});,textStatus) {console.log('ajax error'+jqXHR.responseText);});</script>
  1. The page will then display something like: Your MP is Caroline Lucas MP

How does it work?

The first span just puts the supporter’s postcode in a hidden box so we can reference it later. The next paragraph then shows text to the supporter “Your MP is xxx”, where xxx is filled in by the script.

The script begins by assigning the postcode to a variable, which it gets from the hidden span. The dataurl that will be used to query the contact database is then made, including a filter for the supporter’s postcode. The database ID refers to the Westminster MP database, and the service as seen on Public Data Services. The token is the public token you have on your account.

The data request is then made, using the URL. When it is done, the received JSON information is put in a variable called data. From this, the MP’s name is assembled via a few columns of the received data. Finally, it is inserted into the mpName span from the second line.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.