Submitting standard web forms with Ajax and JSON

Updated on 20-February-2017 at 11:47 AM

Business Catalyst End of life announcement - find out more details.

Introduction

In this example we will use jQuery to submit a webform using Ajax and display the confirmation message on the same page. The form's response message will be returned in JSON format.

We will then need to use a custom function to interpret this response and display the form summary details.

Download and link the jQuery library

The first thing you need to do is to make sure the jQuery library is available in the page we are building this setup. Link it like so:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

Insert the default webform to the page

The next step is to insert the webform you want to use. Simply add it to the page using Module Manager.

Edit your form's action form

Now it is time to customize the form's action field. Switch to the HTML view and:

  1. append "&JSON=1" to the form's action URL
  2. add an ID parameter (e.g. id="contact_form") so we can easily reference the form in the script below

After the steps above the action URL should look something like this:

Insert the custom bits

Next you will need to paste two more elements: the div the form's results will be placed into and the custom javascript function that submits the form using AJAX and interprets the form's response.

Paste the code below just after the form's code:

<!-- This is the div the form's results will be placed into, it is hidden by default -->
<div style="display:none" id="message"></div>

<!-- This is the custom script that does the magic -->
<script type="text/javascript"> function jqsub() { var $f = $('#contact_form'); var $m = $('#message'); $.ajax({ type: 'POST', url: $f.attr('action') + '&amp;JSON=1', data: $f.serialize(), success: function(msg) { var formResponse = eval(msg); // This line evaluates the JSON data and converts it to JSON object. In older version of jQuery you will have to evaluate JSON object as a string. if (formResponse.FormProcessV2Response.success) { $m.addClass('success').fadeIn().html(formResponse.FormProcessV2Response.message); $f.fadeOut(); //Hide the form } }, error: function(msg) { alert('error'+msg); return false; } }); } </script>

Almost there

The last step of the setup is to rig the form to the custom script above. To do this have a look at the script the form came with and replace

theForm.submit();

with

jqsub();

like so:

Done!

Here is how the entire HTML code looks like once all the components are in place:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<form name="catwebformform46465" method="post" onsubmit="return checkWholeForm46465(this)" enctype="multipart/form-data" action="/FormProcessv2.aspx?WebFormID=83516&OID={module_oid}&OTYPE={module_otype}&EID={module_eid}&CID={module_cid}&JSON=1" id="contact_form">
<span class="req">*</span> Required
<table class="webform" cellspacing="0" cellpadding="2" border="0">
<tr>
<td>
<label for="Title">Title</label>
<br />
<select name="Title" id="Title" class="cat_dropdown_smaller">
<option value="317601">DR</option>
<option value="317600">MISS</option>
<option value="317597" selected="selected">MR</option>
<option value="317598">MRS</option>
<option value="317599">MS</option>
<option value="435168">sasasa</option>
<option value="435179">sdad</option>
<option value="435166">vbvbvb</option>
<option value="435167">ytytyty</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="FirstName">First Name <span class="req">*</span>
</label>
<br />
<input type="text" name="FirstName" id="FirstName" class="cat_textbox" maxlength="255" /> </td>
</tr>
<tr>
<td>
<label for="LastName">Last Name <span class="req">*</span>
</label>
<br />
<input type="text" name="LastName" id="LastName" class="cat_textbox" maxlength="255" /> </td>
</tr>
<tr>
<td>
<label for="EmailAddress">Email Address <span class="req">*</span>
</label>
<br />
<input type="text" name="EmailAddress" id="EmailAddress" class="cat_textbox" maxlength="255" /> </td>
</tr>
<tr>
<td>{module_ccsecurity}</td>
</tr>
<tr>
<td>
<input class="cat_button" type="submit" value="Submit" id="catwebformbutton" />
</td>
</tr>
</table>
<script type="text/javascript" src="/CatalystScripts/ValidationFunctions.js?vs=b1818.r472141-phase1"></script>
<script type="text/javascript">
//<![CDATA[
var submitcount46465 = 0;

function checkWholeForm46465(theForm) {
var why = "";
if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
if (why != "") {
alert(why);
return false;
}
if (submitcount46465 == 0) {
submitcount46465++;
jqsub();
return false;
} else {
alert("Form submission is in progress.");
return false;
}
}
//]]>
</script>
</form> <div style="display:none" id="message">Success</div> <script type="text/javascript">
function jqsub() {
var $f = $('#contact_form');
var $m = $('#message');
$.ajax({
type: 'POST',
url: $f.attr('action'),
data: $f.serialize(),
success: function(msg) {
var formResponse = eval(msg); // This line evaluates the JSON data and converts it to JSON object. In older version of jQuery you will have to evaluate JSON object as a string.
if (formResponse.FormProcessV2Response.success) {
$m.addClass('success').fadeIn().html(formResponse.FormProcessV2Response.message);
$f.fadeOut(); //Hide the form
}

},
error: function(msg) {
alert('error'+msg);
return false;
}
});
}
</script>