JavaScript SDK Follow

Web Form JavaScript SDK API

Introduction

Web Forms are used for subscribing new Contacts to Lists, updating their details in Lists, and for unsubscribing them from Lists. Traditional Web Forms are either used as stand-alone web pages, or are embedded in iframes in other web pages.

The JavaScript SDK enables Web Forms to be accessed through JavaScript allowing for a more seamless integration with websites. It is intended for use by web designers and web developers of mixed abilities.

The JavaScript SDK is comprised of three main components; Webform_Xhr, Webform_Session and JavaScript_SDK as described a little below.

Webform_Xhr is intended for use by web designers with basic JavaScript capability. It provides a full implementation of a Web Form in a web page, rendering it as generic HTML with CSS classes on the elements to aid with customising it's appearance.

Webform_Session is suited to web developers who are comfortable working with JavaScript. It provides a simple way to incorporate Contact data into web sites and to subscribe, update and unsubscribe the Contacts in your Lists.

JavaScript_SDK is intended only for advanced JavaScript developers. It provides access to lower level functionality of Web Forms and is used internally by Webform_Xhr and Webform_Session.

Webform_Xhr

Overview

Webform_Xhr is suited to use web designers/developers, requiring little ability with JavaScript. It provides a full implementation of a Web Form in a web page, rendering it as generic HTML with CSS classes on the elements to facilitate customising it's appearance. Optionally, the HTML rendered can be customised by specifying a 'custom renderer', custom validation can be performed via a callback function, and functions can be bound to the form submission events.

Synopsis

/* Constructor */

constructor Webform_Xhr (string url, DOM_Element container ) ;

/* Properties */

public JavaScript_SDK sdk ;

public object custom_renderer ;

/* Functions */

public void initialize ( void ) ;

public void setCustomRenderer (object custom_renderer ) ;

public void setContainer (DOM_Element container ) ;

public void onLoadFields (boolean success, object field_details ) ;

public void onButtonClick ( void ) ;

public void onSubmitResponse (boolean success, object validation_errors ) ;

public void onComplete ( void ) ;

public DOM_Element createField (JavaScript_SDK.Field field, array class_array ) ;

public DOM_Element createLabel (JavaScript_SDK.Field field, array class_array ) ;

public DOM_Element createButton (function on_click, string button_text, array class_array ) ;

public void setOnStatusChange (function on_status_change ) ;

public boolean disableHtml5Inputs (boolean disable ) ;

public void setOnStepChange (function on_step_change ) ;

Example 1

This is a simple example of how to use the Webform_Xhr. It is the default code provided in the Web Form designer.

<div id="form_container"></div>

<script type="text/javascript" src="https://www.vision6.com.au/js/webform_xhr.js"></script>

<script type="text/javascript">

 

    // Get the element to be used as a container for the Web Form.

    var form_container = document.getElementById('form_container');

 

    // Create a Webform_Xhr instance

    var xhr_object = new Webform_Xhr("[XHR endpoint for Web Form from 'add form to website' overlay in List Designer]", form_container);

 

    // Initialize and render the Web Form

    xhr_object.initialize();

 

</script>

Example 2

This example shows how to display a customised 'thank you' page after a Contact completes the Web Form workflow (i.e. after they subscribe, update their profile or unsubscribe).

<div id="form_container"></div>

<script type="text/javascript" src="https://www.vision6.com.au/js/webform_xhr.js"></script>

<script type="text/javascript">

 

    // Create a Webform_Xhr instance

    var xhr_object = new Webform_Xhr("[XHR endpoint for Web Form from 'add form to website' overlay in List Designer]");

 

    // Set the container for the Web Form

    var form_container = document.getElementById('form_container');

    xhr_object.setContainer(form_container);

 

    // Define a function for creating onStepChange callback handlers

    function thankyouPageRenderer(xhr_object, form_container) {

        return function(current_step) {

            if (xhr_object.sdk.isLastStep()) {

                form_container.innerHTML = '<b>Thank you!</b>';

            }

        };

    };

 

    // Add the onStepChange handler

    xhr_object.setOnStepChange(thankyouPageRenderer(xhr_object, form_container));

 

    // Initialize and render the Web Form

    xhr_object.initialize();

 

</script>

Example 3

This example shows of how to use a custom renderer to customise the Web Form output by Webform_Xhr, and to implement custom input validations.

<div id="form_container"></div>

<script type="text/javascript" src="https://www.vision6.com.au/js/webform_xhr.js"></script>

<script type="text/javascript">

 

    function Custom_Renderer(xhr_object) {

        this.xhr_object = xhr_object;

    }

 

    Custom_Renderer.prototype.createLabel = function(field, class_array) {

        // Change the label for text area values

        if (field.getType() == JavaScript_SDK.Field.TYPE_TEXTAREA) {

            var label = document.createElement('label');

            label.setAttribute('for', field.getId());

            label.appendChild(document.createTextNode(field.getDisplayName()));

            label.appendChild(document.createElement('br'));

            label.appendChild(document.createTextNode('(Please keep this as concise as possible; no more than 100 characters)'))

            return label;

        }

 

        // If there is something we don't want to customise, we can just return the Webform_Xhr function instead of reimplementing

        // Return the default label for everything else

        return this.xhr_object.createLabel(field, class_array);

    };

 

    Custom_Renderer.prototype.createField = function(field, class_array) {

        // Add a custom class to text area inputs

        if (field.getType() == JavaScript_SDK.Field.TYPE_TEXTAREA) {

            class_array.push('my-textarea-class');

        }

        return this.xhr_object.createField(field, class_array);

    };

 

    Custom_Renderer.prototype.createButton = function(on_click, button_text, class_array) {

        // Use custom text on the button.

        button_text = 'Click here to submit!';

 

        // Use the Webform_Xhr function to create the button

        var button = document.createElement('BUTTON');

        button.appendChild(document.createTextNode(button_text));

        button.setAttribute('type', 'button');

        button.className = class_array.join(' ') + ' my_custom_button_class';

 

        function custom_on_click(event) {

            // Custom validation: Restrict textarea input values to 100 characters

            var textareas = document.getElementsByClassName('my-textarea-class');

            for (var i = 0; i < textareas.length; i++) {

                if (textareas[i].value.length > 100) {

                    textareas[i].focus();

                    alert('Please keep the value shorter than 100 characters.');

                    return false;

                }

            }

 

            return on_click(event);

        }

 

        button.addEventListener('click', custom_on_click, false);

 

        return button;

    };

 

    // Create a Webform_Xhr instance

    var xhr_object = new Webform_Xhr("[XHR endpoint for Web Form from 'add form to website' overlay in List Designer]");

 

    // Set the container for the Web Form

    var form_container = document.getElementById('form_container');

    xhr_object.setContainer(form_container);

 

    // Add the custom renderer

    var custom_renderer = new Custom_Renderer(xhr_object);

    xhr_object.setCustomRenderer(custom_renderer);

 

    // Initialize and render the Web Form

    xhr_object.initialize();

 

</script>

Constructor

Webform_Xhr ( url, container )

Creates a new Web Form object for the Web Form at the given URL. The 'url' value for a Web Form can be found on the 'JavaScript SDK' tab of the 'add form to website' dialog in the Web Form designer. The 'container' can be any DOM element in the document, including a <FORM>. If anything other than a <FORM> is passed, a <FORM> element will be created around the rest of the Web Form elements when it is rendered.

Parameters:

NameTypeDescription

urlstringURL for the Web Form XHR endpoint

containerDOM_Elementthat the Web Form should be rendered in; optional.

Properties

JavaScript_SDK sdk = [instanceof JavaScript_SDK]

A JavaScript_SDK instance that is used internally.

object custom_renderer = null

Used internally, this is an object that renders components in a Web Form in a custom manner.

Functions

initialize ()

Initializes the Web Form, including making all necessary XHR requests and rendering it.

setCustomRenderer ( custom_renderer )

Allows a custom renderer to be added to a Web Form. A custom renderer must implement three functions: createField, createLabel and createButton.

var example_custom_renderer = {

    createLabel: function(JavaScript_SDK.Field field, array class_array) {

        // Should return a DOM_Element that will act as a label for the field.

    },

    createField: function(JavaScript_SDK.Field field, array class_array) {

        // Should return a DOM_Element that will act as an input.

    },

    createButton: function(function on_click, string button_text, array class_array) {

        // Should return a DOM_Element that will act as a button, with event listeners attached.

    }

}

Parameters:

NameTypeDescription

custom_rendererobjectthat implements three functions: createField, createLabel and createButton

setContainer ( container )

Allows the container element for the Web Form to be set. This can be set in the constructor instead if preferred.

Parameters:

NameTypeDescription

containerDOM_Elementthat Web Form should be rendered in

onLoadFields ( success, field_details )

Function invoked internally when field details are loaded via XHR. This function should only be invoked or overridden by advanced JavaScript developers. When invoked it clear the existing Web Form and re-renders it for the current Web Form step.

Parameters:

NameTypeDescription

successbooleantrue if the fields were loaded, false otherwise

field_detailsobjectwith field identifier / field properties pairs

onButtonClick ()

Function invoked when the Web Form submit button is clicked. This function should only be invoked or overridden by advanced JavaScript developers. When invoked it validates and then serializes the Web Form data, and submits it if no errors were found. On the last step of the Web Form it invokes the Webform_XHR::onComplete() function.

onSubmitResponse ( success, validation_errors )

Function invoked internally when after the submission of a Web Form via XHR. This function should only be invoked or overridden by advanced JavaScript developers. When invoked it displays any validation errors. If there were no errors it loads and displays the next step of the Web Form.

Parameters:

NameTypeDescription

successbooleantrue if the the Web Form submission succeeded, false otherwise

validation_errorsobjectwith field identifier / validation error pairs

onComplete ()

Function invoked internally when a Web Form is completed. This function should only be invoked or overridden by advanced JavaScript developers. When invoked it resets and re-initializes the Web Form, rendering the first step.

createField ( field, class_array ) : DOM_Element

Function that is invoked internally for creating the input elements for the Web Form field. The behaviour of this function can be overridden by implementing a 'custom_renderer'. The returned DOM_Element is appended to the Web Form.

Parameters:

NameTypeDescription

fieldJavaScript_SDK.Fieldto create input elements for

class_arrayarrayof string CSS class names associated with the field by default

Returns:

DOM_Elementincluding input controls for the field

createLabel ( field, class_array ) : DOM_Element

Function that is invoked internally for creating the a label for the Web Worm field. The behaviour of this function can be overridden by implementing a 'custom_renderer'. The returned DOM_Element is appended to the Web Form.

Parameters:

NameTypeDescription

fieldJavaScript_SDK.Fieldto create a label for

class_arrayarrayof string CSS class names associated with the field label by default

Returns:

DOM_Elementincluding a label for the field

createButton ( on_click, button_text, class_array ) : DOM_Element

Function that is invoked internally for creating the a submit button for the Web Form field. The behaviour of this function can be overridden by implementing a 'custom_renderer'.

Parameters:

NameTypeDescription

on_clickfunctionthat should be bound to the returned DOM_Element

button_textstringthat was configured in the Web Form designer

class_arrayarrayof string CSS class names associated with the button by default

Returns:

DOM_Elementincluding a clickable submit button for the Web Form

setOnStatusChange ( on_status_change )

A function can be bound to the Webform_Xhr that is invoked each time the Web Form changes to a new step (including the initial load). This allows other events to be triggered or the page to be customised for each Step. The function is passed a single parameter; a number that matches one of the JavaScript_SDK.SUBSCRIBE_STEP_*, JavaScript_SDK.UPDATE_STEP_* or JavaScript_SDK.UNSUBSCRIBE_STEP_* constant values.

Parameters:

NameTypeDescription

on_status_changefunctionto be invoked when the Web Form Step changes

disableHtml5Inputs ( disable ) : boolean

By default HTML 5 input types (date, datetime_local, number, email and tel) will be used in Web Forms where browsers support them. If disabled, text inputs or select elements will be used instead.

Parameters:

NameTypeDescription

disablebooleanOptional; true enables the use of HTML 5 input types, false enables them

Returns:

booleantrue if HTML 5 inputs are disabled, false otherwise

setOnStepChange ( on_step_change )

A function can be bound to the Webform_Xhr that is invoked each time the Web Form changes to a new step (including the initial load). This allows other events to be triggered or the page to be customised for each Step. The function is passed a single parameter; a number that matches one of the JavaScript_SDK.SUBSCRIBE_STEP_*, JavaScript_SDK.UPDATE_STEP_* or JavaScript_SDK.UNSUBSCRIBE_STEP_* constant values.

Parameters:

NameTypeDescription

on_step_changefunctionto be invoked when the Webform Step changes

Webform_Session

Overview

Webform_Session allows Web Forms to be treated as a data source in your web page and is suitable for web developers who are comfortable working with JavaScript. It provides a simple way to subscribe new Contacts, or to update and unsubscribe existing ones. The 'login' status of the Contact is preserved in the browser using a cookie, allowing updates to be made across multiple web page and browsing sessions.

Synopsis

/* Constructor */

constructor Webform_Session (string subscribe_url, string update_profile_url, string unsubscribe_url ) ;

/* Properties */

public JavaScript_SDK subscribe_sdk ;

public JavaScript_SDK update_profile_sdk ;

public JavaScript_SDK unsubscribe_sdk ;

/* Functions */

public boolean subscribe (object values, function callback ) ;

public boolean login (object values, function callback, boolean do_not_subscribe ) ;

public boolean update (object values, function callback ) ;

public boolean unsubscribe (object values, function callback ) ;

public boolean logout ( void ) ;

public boolean resumeSession (function callback, number contact_id, string contact_key ) ;

public boolean isLoggedIn ( void ) ;

public JavaScript_SDK.fields getDetails ( void ) ;

public string get (string field_identifier ) ;

public boolean set (string field_identifier, string value, function callback ) ;

public boolean sessionPersists (boolean cookie_persists ) ;

Example 1

The example below, albeit somewhat contrived, demonstrates how Webform_Session can be used to subscribe and update Contacts, or to load and use Contact data within a web page.

This example makes the assumption that a List has two fields; 'Email' and 'First Name'. The Subscribe Web Form captures an email address that is also used for logging in to the Update Profile and Unsubscribe Web Forms. The Update Profile Web Form contains the Contact's 'First Name'.

<script type="text/javascript" src="https://www.vision6.com.au/js/webform_xhr.js"></script>

<script type="text/javascript"><!--

 

    // Note: This example assumes there is a List with 'Email' and 'First Name' fields.

    //       The subscribe form and the update profile / unsubscribe login forms require only 'Email'.

    //       The update profile form includes the 'First Name' field.

 

    var subscribe_url = "[XHR endpoint for subscribe Web Form from 'add form to website' overlay in List Designer]";

    var update_profile_url = "[XHR endpoint for Update Profile Web Form from 'add form to website' overlay in List Designer]";

    var unsubscribe_url = "[XHR endpoint for Unsubscribe Web Form from 'add form to website' overlay in List Designer]";

 

    var session = new Webform_Session( subscribe_url, update_profile_url, unsubscribe_url );

 

    // Try to resume any previous session...

    session.resumeSession(function() {

        if (session.isLoggedIn()) {

            // Previous session resumed. Greet user...

            return greetContact();

        } else {

            // No previous login. Prompt user to log in.

            loginContact();

        }

    });

 

    function loginContact() {

        // Prompt Contact to enter their email address

        var email = window.prompt('Please enter your email address to continue:');

 

        // Log the Contact in. Note: This will subscribe the Contact if they do not already exist in the List.

        session.login({ 'Email': email }, function() {

            if (session.isLoggedIn()) {

                return greetContact();

            }

            loginContact();

        });

    }

 

    function greetContact() {

        // This will retrieve the Contact's 'First Name' from the List, if there is one.

        var first_name = session.get('First Name');

 

        // Display their first name somewhere

        if (first_name) {

            alert('Hi ' + first_name + '!');

        } else {

            // Prompt Contact to enter their first name

            first_name = window.prompt('Welcome! What should we call you?');

 

            // Update Contact's first name

            session.set('First Name', first_name, greetContact);

        }

    }

 

//--></script>

Example 2

Webform_Session allows multiple Web Form actions to be chained together, responding to a single user event. In this example a visitor to a web page is able to enter their email address to unsubscribe from a List. They are also asked to give a reason for unsubscribing. When they click the button an update verifies that the email address is subscribed to the List and records the reason for unsubscribing. The email is then unsubscribed from the List. The example assumes that the List has:

- two Fields, 'Email' and 'Unsubscribe Reason'

- Update Profile and Unsubscribe Web Forms with just the 'Email' field for login

- Update Profile form that allows the 'Unsubscribe Reason' Field to be updated

<div>

    <label>Email address: <input type="text" id="email"></label><br>

    <label>Reason for unsubscribing: <input type="text" id="reason"></label><br>

    <input type="button" onclick="unsubscribeWithReason();" value="Unsubscribe now">

</div>

<script type="text/javascript" src="https://www.vision6.com.au/js/webform_xhr.js"></script>

<script type="text/javascript"><!--

 

    function unsubscribeWithReason() {

        var update_profile_url = "[XHR endpoint for Update Profile Web Form from 'add form to website' overlay in List Designer]";

        var unsubscribe_url = "[XHR endpoint for Unsubscribe Web Form from 'add form to website' overlay in List Designer]";

 

        JavaScript_SDK.debug = true;

 

        var session = new Webform_Session( null, update_profile_url, unsubscribe_url );

 

        var email = document.getElementById('email').value;

        var reason = document.getElementById('reason').value;

 

        // Record unsubscribe reason...

        session.update({ 'Email': email, 'Unsubscribe Reason': reason }, function(success) {

            if (success) {

                // Unsubscribe...

                session.unsubscribe(null, function(success) {

                    if (success) {

                        alert('Thank you. You have been unsubscribed.');

                    } else {

                        alert('Sorry, but we could not unsubscribe you. Please try again later.');

                    }

                });

            } else {

                alert('Sorry, but we could not find that email address. It may have been unsubscribed already. Please check your email address and try again.');

            }

        });

 

        return false;

    }

 

//--></script>

Constructor

Webform_Session ( subscribe_url, update_profile_url, unsubscribe_url )

Creates a new Webform_Session for a List. The URLs passed should all be for the same List.

Parameters:

NameTypeDescription

subscribe_urlstringURL of the Subscribe Web Form, or null if subscriptions are not required

update_profile_urlstringURL of the Update Profile Web Form, or null if reading of Contact data and updates are not required

unsubscribe_urlstringURL of the Unsubscribe Web Form, or null if unsubscribing is not required

Properties

JavaScript_SDK subscribe_sdk = [instanceof JavaScript_SDK]

JavaScript_SDK instance for the List's Subscribe Web Form. The form is used for subscribing new Contacts and must contain all of the Fields used by the Update Profile login form. It is intended to be used internally.

JavaScript_SDK update_profile_sdk = [instanceof JavaScript_SDK]

JavaScript_SDK instance for the List's Update Profile Web Form. The form is used for updating Contact profiles. It is intended to be used internally.

JavaScript_SDK unsubscribe_sdk = [instanceof JavaScript_SDK]

JavaScript_SDK instance for the List's unsubscribe form. The form is used for unsubscribing Contacts from the List. It is intended to be used internally.

Functions

subscribe ( values, callback ) : boolean

This function attempts to subscribe a new Contact, and then logs in if it succeeds.

Parameters:

NameTypeDescription

valuesobjectfield identifier / value pairs to subscribe Contact with

callbackfunctioninvoked with boolean parameter; true if successful, false otherwise

Returns:

booleantrue is subscription is attempted, false otherwise

login ( values, callback, do_not_subscribe ) : boolean

This function attempts to login as an existing Contact, and subscribes (creates a new Contact) if it can't. Logging in creates a cookie for the entire site that expires after a year. The cookie can be used to resume a session by calling Webform_Session.resume().

Parameters:

NameTypeDescription

valuesobjectfield identifier / value pairs to login or subscribe with

callbackfunctioninvoked with boolean parameter; true if successful, false otherwise

do_not_subscribebooleanflag that can be set to true if the login should not attempt to subscribe a new Contact is a matching one can not be found

Returns:

booleantrue is login is attempted, false otherwise

update ( values, callback ) : boolean

This function attempts to update a Contact. If not already logged in it attempts to login, and will attempt to subscribe (create a new Contact) if it can't.

Parameters:

NameTypeDescription

valuesobjectfield identifier / value pairs of fields to be updated for the Contact

callbackfunctioninvoked with boolean parameter; true if successful, false otherwise

Returns:

booleantrue is an update is attempted, false otherwise

unsubscribe ( values, callback ) : boolean

This function attempts to unsubscribe a Contact. Once unsubscribed the same Contact cannot log back in.

Parameters:

NameTypeDescription

valuesobjectfield identifier / value pairs of fields to be used to log in, or null if already logged in

callbackfunctioninvoked with boolean parameter; true if successful, false otherwise

Returns:

booleantrue is unsubscribe is attempted, false otherwise

logout () : boolean

This function removes the session cookie and flushes any loaded Contact data from memory.

Returns:

booleantrue if successful, false otherwise

resumeSession ( callback, contact_id, contact_key ) : boolean

This function attempts to resume a previous session with the same login key. If either the contact_id or contact_key parameters are omitted or evaluate to false the 'session cookie' will be used if there is one.

Parameters:

NameTypeDescription

callbackfunctioninvoked with boolean parameter; true if successful, false otherwise

contact_idnumberof Contact in List (Optional)

contact_keystringreturned via XHR at previous login (Optional)

Returns:

booleantrue if a session resumption is attempted, false otherwise

isLoggedIn () : boolean

Can be used to determine the current login status of the Update Profile Web Form.

Returns:

booleantrue if thecontact is logged in to the update profile Web Form, false otherwise

getDetails () : JavaScript_SDK.fields

A Contact must be logged in for this to work.

Returns:

JavaScript_SDK.fieldsobject for accessing details of all Fields in the Update Profile Web Form

get ( field_identifier ) : string

Retrieves the value stored against a Contact for a give Field. A Contact must be logged in for this to work.

Parameters:

NameTypeDescription

field_identifierstringidentifier (id, name, etc.) of the Field

Returns:

stringvalue of the field

set ( field_identifier, value, callback ) : boolean

Sets the value stored against a Contact for a give Field. If not logged in, a login attempt is made to see if a matching Contact already exists. If not, an attempt is made to subscribe the Contact.

Note: When setting multiple Field values, using update() will be quicker.

Parameters:

NameTypeDescription

field_identifierstringidentifier (id, name, etc.) of the Field

valuestringvalue to be stored in the Field

callbackfunctioninvoked with boolean parameter; true if successful, false otherwise

Returns:

booleantrue is an update is attempted, false otherwise

sessionPersists ( cookie_persists ) : boolean

Function for controlling how long a session cookie lasts. By default session cookies expire after a year.

Parameters:

NameTypeDescription

cookie_persistsbooleantrue to make cookie expire after a year, false to make it expire at the end of the browser session

Returns:

booleantrue if the session cookie expires after a year, false if it expires at the end of the browser session

JavaScript_SDK

Overview

The JavaScript_SDK object is used internally by the Webform_Xhr and Webform_Session objects, and is only intended for direct use by more advanced JavaScript developers. Most developers will find Webform_Xhr or Webform_Session better suit their needs.

The JavaScript_SDK object manages Web Form workflows, implements XHR requests and caches Web Form Field details to optimise usage.

Synopsis

/* Constants */

const string FORM_SUBSCRIBE ;

const string FORM_UPDATE ;

const string FORM_UNSUBSCRIBE ;

const number SUBSCRIBE_STEP_WEB_FORM ;

const number SUBSCRIBE_STEP_THANK_YOU ;

const number UPDATE_STEP_LOGIN_FORM ;

const number UPDATE_STEP_UPDATE_PROFILE ;

const number UPDATE_STEP_THANK_YOU ;

const number UNSUBSCRIBE_STEP_UNSUBSCRIBE_FORM ;

const number UNSUBSCRIBE_STEP_THANK_YOU ;

/* Constructor */

constructor JavaScript_SDK (string url ) ;

/* Static Properties */

static boolean debug ;

/* Properties */

public string webform_type ;

public JavaScript_SDK.fields_cache fields_cache ;

public JavaScript_SDK.login_details login_details ;

public number webform_step ;

public JavaScript_SDK.fields fields ;

/* Functions */

public string getXhrUrl ( void ) ;

public object getXhrUrlParameters ( void ) ;

public void reset ( void ) ;

public void loadFieldDetails (function callback ) ;

public void submitForm (Object field_data, function callback ) ;

public void setLoginDetails (integer contact_id, string contact_key ) ;

public boolean isUpdateForm ( void ) ;

public boolean isSubscribeForm ( void ) ;

public boolean isUnsubscribeForm ( void ) ;

public boolean isLoginStep ( void ) ;

public boolean isLoggedIn ( void ) ;

public boolean isFirstStep ( void ) ;

public boolean isLastStep ( void ) ;

public void nextStep ( void ) ;

public void goToStep (number step ) ;

public number currentStep ( void ) ;

Example

The Webform_Xhr and Webform_Session objects provided are both examples of how the JavaScript_SDK object can be used.

Predefined Constants

string FORM_SUBSCRIBE = "Subscribe"

Constant for identifying Subscribe type Web Forms.

string FORM_UPDATE = "Update Profile"

Constant for identifying Update Profile type Web Forms.

string FORM_UNSUBSCRIBE = "Unsubscribe"

Constant for identifying Unsubscribe type Web Forms.

number SUBSCRIBE_STEP_WEB_FORM = 1

Constant for identifying the first step of Subscribe Web Forms, during which a Contact enters their details.

number SUBSCRIBE_STEP_THANK_YOU = 2

Constant for identifying the second, and last, step of Subscribe Web Forms, at which the Contact is thanked for subscribing.

number UPDATE_STEP_LOGIN_FORM = 1

Constant for identifying the first step of Update Profile Web Forms, at which Contacts log in by confirming details they have provided previously.

number UPDATE_STEP_UPDATE_PROFILE = 2

Constant for identifying the second step of Update Profile Web Forms, during which a Contact updates their details.

number UPDATE_STEP_THANK_YOU = 3

Constant for identifying the third, and last, step of Update Profile Web Forms, at which the Contact is thanked for updating their details.

number UNSUBSCRIBE_STEP_UNSUBSCRIBE_FORM = 1

Constant for identifying the first step of Unsubscribe Web Forms, at which Contacts log in by confirming details they have provided previously.

number UNSUBSCRIBE_STEP_THANK_YOU = 2

Constant for identifying the second, and last, step of Unsubscribe Web Forms, at which the unsuscribe action is confirmed.

Constructor

JavaScript_SDK ( url )

Creates a new instance of JavaScript_SDK for interacting with the form identified in the URL.

Parameters:

NameTypeDescription

urlstringURL copied from the "add form to website"/"JavaScript SDK" tab in Form Designer

Static Properties

boolean debug = false

Setting JavaScript_SDK.debug to true turns debugging on, where messages are output to the browser console. Debugging is turned off by default.

Properties

string webform_type = webform_type

The type of Web Form the URL passed in the constructor was for: JavaScript_SDK.FORM_SUBSCRIBE, JavaScript_SDK.FORM_UPDATE or JavaScript_SDK.FORM_UNSUBSCRIBE.

JavaScript_SDK.fields_cache fields_cache = [instanceof JavaScript_SDK.fields_cache]

A helper object used for caching and retrieving Web From Field details for each Web Form step.

JavaScript_SDK.login_details login_details = [instanceof JavaScript_SDK.login_details]

A helper object used for storing Web Form login details and determining the current login status.

number webform_step = webform_step

The current Web Form step: One of the JavaScript_SDK.SUBSCRIBE_STEP_*, JavaScript_SDK.UPDATE_STEP_* or JavaScript_SDK.UNSUBSCRIBE_STEP_* constant values.

JavaScript_SDK.fields fields = [instanceof JavaScript_SDK.fields]

A helper object used for managing and inspecting Web Form Fields.

Functions

getXhrUrl () : string

Function for getting the URL that XHR requests should be made to.

Returns:

stringURL for XHR requests

getXhrUrlParameters () : object

Function for getting a key/value paired object with values that need passing in an XHR request for the Web Form.

Returns:

objectkey / value pairs of parameters

reset ()

Resets the Web Form back to the first step, removing any previous login details.

loadFieldDetails ( callback )

Loads the Field details for the current Web Form step, retrieving from the cache if already loaded. The first parameter to the callback function will be true on success and false otherwise. If successful a second parameter, a JavaScript_SDK.fields instance with the details of the Fields loaded, will also be passed to the callback function.

Parameters:

NameTypeDescription

callbackfunctionto be invoked on completion with parameters 'success' and 'fields'

submitForm ( field_data, callback )

Submits the Field values to the Web Form. The first parameter to the callback function will be true on success and false otherwise. If the values submitted are invalid, a second parameter, validation_errors, will be passed to the callback function. validation_errors would be an object with key / value pairs, where the keys are the Field Id's.

Parameters:

NameTypeDescription

field_dataObjectOptional; key / value pairs for the Fields that should be saved. If null or false, the values of the Fields in JavaScript_SDK.fields are submitted

callbackfunctionto be invoked on completion with parameters 'success' and 'validation_errors'

setLoginDetails ( contact_id, contact_key )

Stores the given details in the JavaScript_SDK.login_details object.

Parameters:

NameTypeDescription

contact_idintegerId of the Contact in the List

contact_keystringreturned in the response to a login type Web Form step submission

isUpdateForm () : boolean

Convenience function to check if the Web Form at the URL passed to the constructor was an Update Profile Web Form.

Returns:

booleantrue if the Web Form is an Update Profile Web Form, false otherwise

isSubscribeForm () : boolean

Convenience function to check if the Web Form at the URL passed to the constructor was a Subscribe Web Form.

Returns:

booleantrue if the Web Form is a Subscribe Web Form, false otherwise

isUnsubscribeForm () : boolean

Convenience function to check if the Web Form at the URL passed to the constructor was an Unsubscribe Web Form.

Returns:

booleantrue if the Web Form is a Unsubscribe Web Form, false otherwise

isLoginStep () : boolean

Determines whether or not the current Web Form step is a login step; Update Profile and Unsubscribe Web Forms only.

Returns:

booleantrue if the current Web Form step is a login step, false otherwise

isLoggedIn () : boolean

Determines whether or not the Web Form login step has been completed; Update Profile and Unsubscribe Web Forms only.

Returns:

booleantrue if the Contact has logged in to the Web Form, false otherwise

isFirstStep () : boolean

Determines whether or not the Web Form workflow is at the first step. This is the login step for Update Profile and Unsubscribe Web Forms. For Subscribe Web Forms it is the step the Contact enters their details to subscribe.

Returns:

booleantrue if the Web Form workflow is at the first step, false otherwise

isLastStep () : boolean

Determines whether or not the Web Form workflow is at the last step. This is always a confirmation/thank you step.

Returns:

booleantrue if the Web Form step is the last in the workflow, false otherwise

nextStep ()

Advances the Web Form workflow to the next step. This should normally only be invoked after any login step has been completed. If already on the last step, this has no effect.

goToStep ( step )

Changes the current Web Form step to that given. The number parameter passed should be one of the JavaScript_SDK.SUBSCRIBE_STEP_*, JavaScript_SDK.UPDATE_STEP_* or JavaScript_SDK.UNSUBSCRIBE_STEP_* constant values.

Parameters:

NameTypeDescription

stepnumberof the Web Form step to move to

currentStep () : number

Returns the number that represents the current Web Form step. The number will match one of the JavaScript_SDK.SUBSCRIBE_STEP_*, JavaScript_SDK.UPDATE_STEP_* or JavaScript_SDK.UNSUBSCRIBE_STEP_* constant values.

Returns:

numberof the current Web Form step

JavaScript_SDK.Field

Overview

An object type created by JavaScript_SDK to help work with the raw Field data returned in XHR responses.

Synopsis

/* Constants */

const number TYPE_OTHER ;

const number TYPE_TEXT ;

const number TYPE_HIDDEN ;

const number TYPE_PASSWORD ;

const number TYPE_LABEL ;

const number TYPE_SELECT ;

const number TYPE_MULTIPLE ;

const number TYPE_CHECKBOX ;

const number TYPE_RADIO ;

const number TYPE_TEXTAREA ;

const number TYPE_DATETIME ;

const number TYPE_DECIMAL ;

const number TYPE_CURRENCY ;

const number VALIDATION_EMAIL ;

const number VALIDATION_DATETIME_RANGE ;

const number VALIDATION_DATETIME_FUTURE ;

const number VALIDATION_DATETIME_PAST ;

const number VALIDATION_MOBILE ;

const number VALIDATION_NUMERIC ;

const number VALIDATION_ALPHA ;

const number VALIDATION_ALPHA_NUMERIC ;

const number VALIDATION_INTEGER ;

const number VALIDATION_USERNAME ;

/* Functions */

public string getId ( void ) ;

public string getValue ( use_html5_inputs ) ;

public void setValue (string value ) ;

public string getName ( void ) ;

public string getDisplayName ( void ) ;

public number getType ( void ) ;

public string getInputType ( use_html5_inputs ) ;

public integer getMaxlength ( void ) ;

public integer getColSize ( void ) ;

public integer getRowSize ( void ) ;

public Array getOptions ( void ) ;

public boolean isMandatory ( void ) ;

public boolean isDate ( void ) ;

public boolean hasTime ( void ) ;

public boolean has12HourTime ( void ) ;

public boolean requiresValidation ( void ) ;

public number getValidationType ( void ) ;

public string validate (string value ) ;

public string getPattern ( void ) ;

public string getStep ( void ) ;

public string getMin ( void ) ;

public string getMax ( void ) ;

Predefined Constants

number TYPE_OTHER = 0

Constant to identify unrecognised types of Web Form Field.

number TYPE_TEXT = 1

Constant to identify text type Web Form Fields; usually rendered as <INPUT type="text">

number TYPE_HIDDEN = 2

Constant to identify text type that should be hidden in Web Form Fields; usually rendered as <INPUT type="hidden">

number TYPE_PASSWORD = 3

Constant to identify text type Web Form Fields that contain passwords; usually rendered as <INPUT type="password">.

number TYPE_LABEL = 4

Constant to identify text type Web Form Fields that should be treated as labels.

number TYPE_SELECT = 5

Constant to identify single-select type Web Form Fields; usually rendered as <SELECT>'s.

number TYPE_MULTIPLE = 6

Constant to identify single-select type Web Form Fields; usually rendered as <SELECT multiple>'s.

number TYPE_CHECKBOX = 7

Constant to identify multiple-select type Web Form Fields; usually rendered as <INPUT type="checkbox">'s.

number TYPE_RADIO = 8

Constant to identify single-select type Web Form Fields; usually rendered as <INPUT type="radio">'s.

number TYPE_TEXTAREA = 9

Constant to identify multi-line text type Web Form Fields; usually rendered as <TEXTAREA>'s.

number TYPE_DATETIME = 30

Constant to identify date / date + time type Web Form Fields; usually rendered as some form of date selector.

number TYPE_DECIMAL = 28

Constant to identify decimal number type Web Form Fields; usually rendered as <INPUT type="text"> with input validation.

number TYPE_CURRENCY = 29

Constant to identify currency value type Web Form Fields; usually rendered as <INPUT type="text"> with input validation.

number VALIDATION_EMAIL = 1

Constant to identify Email address validation is required for a Fields value.

number VALIDATION_DATETIME_RANGE = 6

Constant to identify date / date + time validation is required for a Fields value.

number VALIDATION_DATETIME_FUTURE = 9

Constant to identify date / date + time validation is required for a Fields value, where the date must be after a specific time.

number VALIDATION_DATETIME_PAST = 10

Constant to identify date / date + time validation is required for a Fields value, where the date must be before a specific time.

number VALIDATION_MOBILE = 11

Constant to identify Mobile phone number validation is required for a Fields value.

number VALIDATION_NUMERIC = 19

Constant to identify numeric validation is required for a Fields value.

number VALIDATION_ALPHA = 3

Constant to identify alpha validation is required for a Fields value.

number VALIDATION_ALPHA_NUMERIC = 4

Constant to identify alpha-numeric validation is required for a Fields value.

number VALIDATION_INTEGER = 5

Constant to identify integer validation is required for a Fields value.

number VALIDATION_USERNAME = 15

Constant to identify username validation is required for a Fields value.

Functions

getId () : string

The Id of the Field, as returned in the Web Form XHR responses and used to reference Fields in such things as validation errors.

Returns:

stringId of the Field

getValue ( use_html5_inputs ) : string

Retrieves the value of the Field as a string. Fields with multiple values have the values returned as a comma separated list. Date fields have their values in the format 'YYYY-mm-dd HH:ii:ss'.

Parameters:

NameTypeDescription

use_html5_inputs

Returns:

stringvalue of the field

setValue ( value )

Sets the value of the Field as a string. Fields with multiple values should have the values passed as a comma separated list. Date fields should have their values passed in the format 'YYYY-mm-dd HH:ii:ss'.

Parameters:

NameTypeDescription

valuestringvalue of the field

getName () : string

Returns the name of the Field in the List.

Returns:

stringname of the Field

getDisplayName () : string

Returns the display name of the Field in the Web Form.

Returns:

stringdisplay name of the Field

getType () : number

Returns the numeric type of the field. The value will correspond to one of the JavaScript_SDK.Field.TYPE_* constants.

Returns:

numbertype of the field

getInputType ( use_html5_inputs ) : string

For Web Form Fields that are typically rendered as <INPUT> elements, this function returns the value of the 'type' attribute best suited to it.

Parameters:

NameTypeDescription

use_html5_inputs

Returns:

string<INPUT>.type attribute value

getMaxlength () : integer

For text-type Fields, this returns the maximum byte length of the value that can be stored in it.

Returns:

integermaximum length of the field value

getColSize () : integer

For multi-line text inputs typically using <TEXTAREA> elements, this is the value usually applied to the COLS attribute.

Returns:

integernumber of columns to render <TEXTAREA> with

getRowSize () : integer

For multi-line text inputs typically using <TEXTAREA> elements, this is the value usually applied to the ROWS attribute.

Returns:

integernumber of rows to render <TEXTAREA> with

getOptions () : Array

For Field types that offer a selection of pre-defined values, this returns an array of those values. For date range Fields, this returns an array containing two values; the start and end of the range.

Returns:

Arrayof options

isMandatory () : boolean

Fields that must be included in the submission of the Web Form are 'mandatory'. This function returns 'true' only for Fields that are mandatory.

Returns:

booleantrue if the Field is mandatory, false otherwise

isDate () : boolean

This function returns 'true' only for Fields that contain a date type field; date-times, future and past dates, and date ranges.

Returns:

booleantrue if the Field is a date type

hasTime () : boolean

This function returns true if the Field is a date type field and contains a time component.

Returns:

booleantrue for date-time Fields with a time component, false otherwise

has12HourTime () : boolean

This function returns true if the Field is a date type field and should be rendered with a 12-hour clock (with AM/PM) time component.

Note: This does not change the formats of values for the getValue or setValue methods, which should always be in 24-hour clock time.

Returns:

booleantrue for date-time Fields with a 12-hour clock time component, false otherwise

requiresValidation () : boolean

Returns true for Fields that require values to be in a specific format such as dates, Email addresses and Mobile numbers.

Returns:

booleantrue for Fields that require input validation

getValidationType () : number

For Fields that require validation, this function identifies the validation type required. The return value will be one of the JavaScript_SDK.Field.VALIDATION_* constants.

Returns:

numbertype of validation required

validate ( value ) : string

Validates a given value for the Field. If invalid a generic error message is returned to help identify what is wrong with the value. null is returned if the value is valid.

Parameters:

NameTypeDescription

valuestringvalue to be validated for the Field

Returns:

stringvalidation error message or null if valid

getPattern () : string

Returns a regular expression that can be applied to an HTML 5's input pattern attribute, that matches all valid values for the Web Form Field.

Returns:

stringHTML 5 <INPUT>.pattern attribute value

getStep () : string

Returns a regular expression that can be applied to an HTML 5's input step attribute, that represents the smallest increments permitted for values of the Web Form Field.

Returns:

stringHTML 5 <INPUT>.step attribute value

getMin () : string

Returns a regular expression that can be applied to an HTML 5's input min attribute, that represents the minimum value permitted for values of the Web Form Field.

Returns:

stringHTML 5 <INPUT>.min attribute value

getMax () : string

Returns a regular expression that can be applied to an HTML 5's input max attribute, that represents the maximum value permitted for values of the Web Form Field.

Returns:

stringHTML 5 <INPUT>.max attribute value

JavaScript_SDK.fields_cache

Overview

Intended for internal use by JavaScript_SDK, this object handles the caching of the raw Field data for the Web Form steps.

Synopsis

/* Functions */

public void cache (number webform_step, object fields ) ;

public object get (number webform_step ) ;

Functions

cache ( webform_step, fields )

Caches a raw data object, as returned in XHR requests for Field details, for the given step. The webform_step parameter should be one of the JavaScript_SDK.SUBSCRIBE_STEP_*, JavaScript_SDK.UPDATE_STEP_* or JavaScript_SDK.UNSUBSCRIBE_STEP_* constant values.

Parameters:

NameTypeDescription

webform_stepnumberof the Web Form step the Field data relates to

fieldsobjectkey / value object, as returned in XHR requests for Field details

get ( webform_step ) : object

Retrieves the data cached by the cache() function. The webform_step parameter should be one of the JavaScript_SDK.SUBSCRIBE_STEP_*, JavaScript_SDK.UPDATE_STEP_* or JavaScript_SDK.UNSUBSCRIBE_STEP_* constant values.

Parameters:

NameTypeDescription

webform_stepnumberof the Web Form step to retrieve Field data for

Returns:

objectkey / value object that was cached, or null

JavaScript_SDK.login_details

Overview

Intended for internal use by JavaScript_SDK, this object handles the caching of the Web Form login state.

Synopsis

/* Functions */

public mixed getContactId ( void ) ;

public boolean hasContactId ( void ) ;

public string getContactKey ( void ) ;

public boolean isLoggedIn ( void ) ;

Functions

getContactId () : mixed

Returns the Id of the logged-in Contact or false if there isn't one.

Returns:

mixedinteger Contact Id or false if not logged in

hasContactId () : boolean

Returns true if a Contact Id is known.

Returns:

booleantrue if a Contact Id has been identified, false otherwise

getContactKey () : string

When a Contact logs in to update their profile the login response contains a 'contact key' that must be included to perform any updates. This function returns that key if known, or false otherwise.

Returns:

stringkey required for all updates and unsubscribes

isLoggedIn () : boolean

Determines whether or not there is a Contact currently logged in to the Web Form.

Returns:

booleantrue if logged-in, false otherwise

JavaScript_SDK.fields

Overview

Intended for internal use by JavaScript_SDK, this object provides convenience functions for handling the Web Form Fields of a step.

Field identifiers accepted by functions can be a Field Id, a Field name, a Field display name or the index of the Field in the initial XHR response, matched in that order.

Synopsis

/* Functions */

public JavaScript_SDK.Field getFieldObject (string field_identifier ) ;

public object getFieldValues ( void ) ;

public JavaScript_SDK.Field setFieldValue (string field_identifier, string value ) ;

public mixed validateFieldValue (string field_identifier, string value ) ;

public object getValidationErrors (object field_data ) ;

public object getFieldIds ( void ) ;

Functions

getFieldObject ( field_identifier ) : JavaScript_SDK.Field

Attempts to find a JavaScript_SDK.Field object for a Field matching the given identifier.

Parameters:

NameTypeDescription

field_identifierstringidentifier for the Field

Returns:

JavaScript_SDK.Fieldobject matching the given identifier, or null

getFieldValues () : object

Returns a collection of values for all Fields. The keys on the returned object are the Field Ids.

Returns:

objectkey / value pairs of Field values

setFieldValue ( field_identifier, value ) : JavaScript_SDK.Field

Attempts to set the given value against the identified Field.

Parameters:

NameTypeDescription

field_identifierstringidentifier of the Field

valuestringvalue to be set on the Field

Returns:

JavaScript_SDK.Fieldif the value was set on a Field, null otherwise

validateFieldValue ( field_identifier, value ) : mixed

Attempts to validate the given value for the identified Field.

Parameters:

NameTypeDescription

field_identifierstringidentifier of the Field

valuestringvalue to be validated

Returns:

mixedstring validation error message, or null if valid

getValidationErrors ( field_data ) : object

Attempts to validate the values passed against the Fields matching the identifier keys. If no values are passed all of the current Field values are validated.

Parameters:

NameTypeDescription

field_dataobjectoptional; Field identifier / value pairs to be validated

Returns:

objectkey / validation error pairs for invalid values

getFieldIds () : object

Returns an object with all Field ids as values. The keys are arbitrary Field names that may or may not match actual Field names.

Returns:

objectField identifier / Id pairs for all Fields

Was this article helpful?
0 out of 1 found this helpful
Have more questions? Submit a request