Ajax Quick Comment Form with Master Form .PHP
Ajax can be used with Master Form .PHP to publish a Quick Comment form on your website. The comment form submits without reloading the web page.
After submission, the form is replaced with a confirmation/"thank you" message. The confirmation message may be personalized.
When the form is submitted, Master Form .PHP can send one or more customized emails, formatted plain text or HTML, with or without attachments. It's simple to set up with the software's control panel.
Master Form .PHP automatically stores the form data in a MySQL database.
If your ISP messes with your email or your server's mailing software temporarily goes on the fritz, retrieve the data from the MySQL database. The data can be exported as a CSV file at any time by using the Master Form .PHP control panel.
The method described in this article is not limited to comment forms. Survey forms, price request forms, catalog download forms — those and other types of forms can be implemented.
How It Works
When the Quick Comment form's submit button is clicked:
-
A "Processing..." message replaces the form. (Lets the form user know things are proceeding and also prevents double-clicking the submit button.)
-
Ajax submits the Quick Comment form to Master Form .PHP
-
Master Form .PHP processes the form:
- Stores the data in a MySQL database.
- Sends any emails specified in preferences.
- Returns the confirmation page to the Ajax engine.
-
The Ajax engine then replaces the form with the visible content of the confirmation page.
During the entire submission process, the page containing the form remains in the window. The only change is the form itself, which is replaced with the confirmation page content.
Live Example
Here is a live example. When you use it, an email is sent to me with your message.
(It's OK. Go ahead and say, "Hi ya!")
The source code for the form and JavaScript (including the Ajax engine) for the above example are further below in the article – ready for copying and pasting.
Two Limitations with Ajax
1.
Ajax can submit only to software on the same domain. Thus, Master Form .PHP must be installed on the domain where the Ajax Quick Comment form is located. It's an Ajax limitation, not a limitation of Master Form .PHP (which can otherwise process forms from any domain).
Note: The Master Form .PHP license allows you to install the software on any domains you own. It is not restricted to only one domain.
2.
Another limitation with the Ajax-submitted form is no file uploads. Master Form .PHP easily handle file uploads from regularly-submitted forms. But not with the Ajax-submitted form.
How To Implement Quick Comment With Ajax
Before doing any of the below steps, go to the Master Form .PHP control panel and click "Create Form Setup".
There, specify a name/label for the setup. It's the first form field on the page. Don't specify anything else, just scroll down to the bottom of the page and click the "Create Form Setup" menu item.
What you just did is create a MySQL table for the form data.
Master Form .PHP will give you a hidden field your form needs to have. Make a note of it or come back later and get it with the "Get Setup Info" menu item.
After the below steps are done, go back to the control panel, click the "Edit Setup" menu item, and specify any emails you want sent to you when the Quick Comment form is used.
Step 1:
Create a form or make a copy of a form you are already using somewhere.
At this point, it doesn't matter what the action URL is. We'll customize the form tag in a moment.
Paste the form into a test web page. If JavaScript for error checking comes with the form, paste that into the web page, too.
Step 2:
Put a div tag above the form and a cancel div tag below the form.
The div tag needs to have an id, its value unique on the page. (Values of an id attribute begin with a letter and are composed of letters, numbers, and/or underscore characters.)
Specify a height and width for the div. Otherwise, the div's size is likely to shift as it adjusts for the different content it will contain. When the form is submitted, the div contains a
The CSS attribute overflow:auto can be specified to put scrollbars on the div if the content is larger than will fit.
Example div tag to contain the form:
<div id="div_with_form" style="width:150px; height:120px; overflow:auto;"> [form goes here] </div>
Step 3:
We'll do 2 things with the form.
1.
Replace the entire <form...> tag with this:
<form id="the_form" onsubmit="return SubmitFormViaAjax()">
The id value needs to be unique. Change the id value if needed or desired.
2.
Below the form tag, insert the hidden field Master Form .PHP gave you when you created the form setup. If you didn't make a note of it at the time, it can be obtained with the Master Form .PHP control panel "Get Setup Info" menu item.
It looks something like that:
<input type="hidden" name="MySQL_table_key" value="1">
The value may be a different number.
Step 4:
Make a confirmation page for Master Form .PHP to use when the form is submitted to it. The manual has instructions. The content can say something appropriate, like "Thank you."
Here is an example:
<html> <body style="margin:0;"> <?php $InstallationDirectory = "/mfphp"; include($_SERVER["DOCUMENT_ROOT"]."$InstallationDirectory/MasterFormInclude.php"); ?> <p style="font-size:16px;"> <b>Thank you!</b> </p> <p style="font-size:14px;"> Any response will be sent to <?php echo(@$_POST["email"]); ?> </p> </body> </html>
The [quick start] link on the home page of the Master Form .PHP control panel contains the exact 4 lines of PHP code you need to replace the 4 lines in the above example. Copy and paste.
See the Master Form .PHP built-in user manual for information to personalize the confirmation page.
Because this confirmation page will replace the Quick Comment form, refrain from giving the page a style sheet. Use only inline styles. Otherwise, the style sheet of the confirmation page is likely to override existing styles on the web page containing the form.
Step 5:
Paste this Ajax code into the web page with the Quick Comment form, or import it from an external file. The code can be above or below the form, in the web page HEAD or BODY area.
<script type="text/javascript"> /* Ajax for Quick Comment Form Version 1.0 January 4, 2011 Will Bontrager https://www.willmaster.com/ Copyright 2011 Bontrager Connection, LLC Bontrager Connection, LLC grants you a royalty free license to use or modify this software provided this notice appears on all copies. This software is provided "AS IS," without a warranty of any kind. */ /* C U S T O M I Z A T I O N */ /* In 3 places */ // Place 1. // Specify the URL of the confirmation page that // Master Form .PHP will use. Specify the URL // relative to document root. For example, if // the absolute URL is // http://example.com/thankyou.php // then the relative URL is // /thankyou.php var ConfirmationPage = "/thankyou.php"; // Place 2. // Specify the id value of the div containing the form. var IDvalueOfDiv = "div_with_form"; // Place 3. // Specify the id value of the form tag. var IDvalueOfFormTag = "the_form"; /* End of customization */ /************************/ function SubmitFormViaAjax() { var divid = document.getElementById(IDvalueOfDiv); var topmargin = divid.style.height ? "margin-top:"+parseInt(parseInt(divid.style.height)/3)+"px; " : ""; var processing = '<div style="' + topmargin + 'border:3px dotted black; padding:10px 0 10px 0; font-weight:bold; text-align:center;">' + 'Processing ...' + '<'+'/div>'; var data = new String; var form = document.getElementById(IDvalueOfFormTag); var fieldvalue = new Array; for(var i=0; i<form.length; i++) { var type = form[i].type ? form[i].type : false; if(type) { if(type=="text" || type=="textarea" || type=="submit" || type=="hidden") { fieldvalue.push(escape(form[i].name)+"="+escape(form[i].value)); } if(type=="checkbox") { if(form[i].checked) { fieldvalue.push(escape(form[i].name)+"="+escape(form[i].value)); } } if(type=="radio") { if(form[i].checked) { fieldvalue.push(escape(form[i].name)+"="+escape(form[i].value)); } } if(type.indexOf("select")==0) { for(var ii=0; ii<form[i].length; ii++) { if(form[i][ii].selected) { fieldvalue.push(escape(form[i].name)+"="+escape(form[i][ii].value)); } } } } } var data = fieldvalue.join("&"); fieldvalue = Array(); divid.innerHTML = processing; var http = GetConnection(); http.open("POST",ConfirmationPage,true); http.onreadystatechange = function() { SubmitDataReceiveResponse(http); }; http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", data.length); http.setRequestHeader("Connection", "close"); http.send(data); return false; } // function SubmitFormViaAjax() function GetConnection() { var httpRequest; if(window.XMLHttpRequest) { try { httpRequest = new XMLHttpRequest(); } catch(e) {} } else if(window.ActiveXObject) { try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} } } if(! httpRequest) { alert('\n\nSorry, unable to open a connection to the server.'); return false; } return httpRequest; } // function GetConnection() function SubmitDataReceiveResponse(doc) { var re = new RegExp("<!--BETWEEN-->","g") try { if (doc.readyState == 4) { if(doc.status == 200) { var content = doc.responseText; document.getElementById(IDvalueOfDiv).innerHTML = content; } else { alert('\n\nContent request error, status code:\n'+doc.status+' '+doc.statusText); document.getElementById(IDvalueOfDiv).innerHTML = ""; } } } catch(error) { alert('Error: '+error.name+' -- '+error.message); } } // function SubmitDataReceiveResponse() </script>
Step 6:
Open the Master Form .PHP control panel's "Edit Setup" menu item to update the setup previously created for the Quick Comment form.
Scroll down to near the bottom of the page to the "Post-submission Email" section. Click
The only thing that is required is the To: address. However, it is prudent to also specify a subject line.
If the email body is left blank, all the form data will be sent in the email. To format the email, type anything you want in it and use [[FieldName]] wherever you want to insert form field information.
Example:
Email address [[email]] was provided.
Form field names between the double square brackets are case sensitive.
More emails can be specified by clicking
Tidying Up
With Ajax, the JavaScript Ajax engine needs to be on the page where it will be used. And, the URL Ajax interacts with needs to be on the same domain as the web page with the Ajax engine.
Therefore, the web page with the Quick Comment form needs to be on the server. The form can't be tested otherwise.
Ajax submits to the Master Form .PHP confirmation page. Both Master Form .PHP and the confirmation page need to be on the same domain as the Quick Comment form.
It can seem like a lot of things to keep track of. But it's only three, and they are all on the same server:
- The Quick Comment form web page.
- The confirmation page.
- A Master Form .PHP installation.
The Master Form .PHP control panel's [quick start] link shows you how to make the confirmation page.
Master Form .PHP itself is easy to install. Once installed on your server, you can use the software to process pretty much any form and, unless using Ajax, forms located at any website.
The Code for the Example
Here is the code for the form and JavaScript with Ajax for the Quick Comment form example near the beginning of this article.
<div id="div_with_form" style="width:160px; height:135px; overflow:auto;"> <form id="the_form" onsubmit="return SubmitFormViaAjax()"> <input type="hidden" name="MySQL_table_key" value="1"> <div><input type="text" id="name" name="name" style="width:150px;" value="Name" onfocus="if(this.value=='Name'){this.value='';}"></div> <div><input type="text" id="email" name="email" style="width:150px;" value="Email" onfocus="if(this.value=='Email'){this.value='';}"></div> <div><textarea id="message" name="message" style="width:150px; height:50px;" onfocus="if(this.value=='Message'){this.value='';}">Message</textarea></div> <div><input type="submit" onclick="return ErrorCheckFields()" id="submitter" name="submitter" style="width:150px;" value="Send Message"></div> </form> <script type="text/javascript"> function ErrorCheckFields(){ var ErrorMessage = new Array(); var re = /[\w\_\-\.]@[\w\_\-\.]/; if( (!document.getElementById("name")) || (document.getElementById("name").value.length<1) ) { ErrorMessage.push("The Text field \"Name\" is required."); } if( (!document.getElementById("email")) || (document.getElementById("email").value.length<1) ) { ErrorMessage.push("The Text field \"Email\" is required."); } if( document.getElementById("email") ) { var ts = document.getElementById("email").value; if( ts.length && (!re.test(ts)) ) { ErrorMessage.push("The text field \"Email\" requires a valid email address."); } } if( (!document.getElementById("message")) || (document.getElementById("message").value.length<1) ) { ErrorMessage.push("The Textarea Box field \"Message\" is required."); } if(ErrorMessage.length) { alert(ErrorMessage.join("\n\n")); return false; } else { return true; } } </script> </div> <script type="text/javascript"> /* Ajax for Quick Comment Form Version 1.0 January 4, 2011 Will Bontrager https://www.willmaster.com/ Copyright 2011 Bontrager Connection, LLC Bontrager Connection, LLC grants you a royalty free license to use or modify this software provided this notice appears on all copies. This software is provided "AS IS," without a warranty of any kind. */ /* C U S T O M I Z A T I O N */ /* In 3 places */ // Place 1. // Specify the URL of the confirmation page that // Master Form .PHP will use. Specify the URL // relative to document root. For example, if // the absolute URL is // http://example.com/thankyou.php // then the relative URL is // /thankyou.php var ConfirmationPage = "/library/supportingfiles/mfphpthankyou.php"; // Place 2. // Specify the id value of the div containing the form. var IDvalueOfDiv = "div_with_form"; // Place 3. // Specify the id value of the form tag. var IDvalueOfFormTag = "the_form"; /* End of customization */ /************************/ function SubmitFormViaAjax() { var divid = document.getElementById(IDvalueOfDiv); var topmargin = divid.style.height ? "margin-top:"+parseInt(parseInt(divid.style.height)/3)+"px; " : ""; var processing = '<div style="' + topmargin + 'border:3px dotted black; padding:10px 0 10px 0; font-weight:bold; text-align:center;">' + 'Processing ...' + '<'+'/div>'; var data = new String; var form = document.getElementById(IDvalueOfFormTag); var fieldvalue = new Array; for(var i=0; i<form.length; i++) { var type = form[i].type ? form[i].type : false; if(type) { if(type=="text" || type=="textarea" || type=="submit" || type=="hidden") { fieldvalue.push(escape(form[i].name)+"="+escape(form[i].value)); } if(type=="checkbox") { if(form[i].checked) { fieldvalue.push(escape(form[i].name)+"="+escape(form[i].value)); } } if(type=="radio") { if(form[i].checked) { fieldvalue.push(escape(form[i].name)+"="+escape(form[i].value)); } } if(type.indexOf("select")==0) { for(var ii=0; ii<form[i].length; ii++) { if(form[i][ii].selected) { fieldvalue.push(escape(form[i].name)+"="+escape(form[i][ii].value)); } } } } } var data = fieldvalue.join("&"); fieldvalue = Array(); divid.innerHTML = processing; var http = GetConnection(); http.open("POST",ConfirmationPage,true); http.onreadystatechange = function() { SubmitDataReceiveResponse(http); }; http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", data.length); http.setRequestHeader("Connection", "close"); http.send(data); return false; } // function SubmitFormViaAjax() function GetConnection() { var httpRequest; if(window.XMLHttpRequest) { try { httpRequest = new XMLHttpRequest(); } catch(e) {} } else if(window.ActiveXObject) { try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} } } if(! httpRequest) { alert('\n\nSorry, unable to open a connection to the server.'); return false; } return httpRequest; } // function GetConnection() function SubmitDataReceiveResponse(doc) { var re = new RegExp("<!--BETWEEN-->","g") try { if (doc.readyState == 4) { if(doc.status == 200) { var content = doc.responseText; document.getElementById(IDvalueOfDiv).innerHTML = content; } else { alert('\n\nContent request error, status code:\n'+doc.status+' '+doc.statusText); document.getElementById(IDvalueOfDiv).innerHTML = ""; } } } catch(error) { alert('Error: '+error.name+' -- '+error.message); } } // function SubmitDataReceiveResponse() </script>
See the Master Form .PHP [quick start] link for code to create the conformation page.
Getting Master Form .PHP
Click: Master Form .PHP for the sales page.
I think you will be pleased with all it can do, how it works. Like all our commercial software, it has the "It works like we say it does or you get your money back" guarantee.
Will Bontrager