Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryManaging Website Forms

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Ajax Form System

Submitting a form and getting the response on the same page can be desirable for many implementations.

Examples of types of forms that can benefit from on-page response are short surveys, calculators, even contact forms. (We do it with a contact form at the custom software page — tap on "Click to tell us about your project.")

One of the primary benefits of an Ajax form system is that no additional page load is necessary. The site user's place on the page isn't interrupted. Users don't get sent to another page and have to tap "back" to continue with the previous page.

This article contains a system for publishing a web page form and submitting it with Ajax.

Ajax submits the form information to a PHP or other language form-handling script. Any form-handling script that can accept submissions from web page forms can be used with this system.

When the form-handling script responds, Ajax publishes the response on the same web page as the form. The response may replace/overwrite the form or it may be published elsewhere on the page.

Build the HTML form you want to use with this system (except no file uploads can be done).

A Working Ajax Form Example

Here is an example form. The response from the form-handling script is published below the form.

Name:

Favorite color:

Why is that your favorite color?

Submission response will be published here.

Implementing the Ajax Form System

Before anything else, let me give you the JavaScript to use. No customization is required.

Put the JavaScript somewhere on the web page with the form or import it from an external file.

<script>
function AjaxFormPost(formid,divid,posturl)
{
   var http = new XMLHttpRequest();
   if(! http) { alert("Unable to establish connection."); return; }
   var params = new Array();
   fid = document.getElementById(formid);
   for(var i=0; i<fid.length; i++)
   {
      if(fid[i].tagName=="TEXTAREA")
      {
         params.push(encodeURIComponent(fid[i].name)+"="+encodeURIComponent(fid[i].value));
         continue;
      }
      if(fid[i].tagName=="INPUT")
      {
         if((fid[i].type=="radio" || fid[i].type=="checkbox") && fid[i].checked)
         {
            params.push(encodeURIComponent(fid[i].name)+"="+encodeURIComponent(fid[i].value));
            continue;
         }
         params.push(encodeURIComponent(fid[i].name)+"="+encodeURIComponent(fid[i].value));
         continue;
      }
      if(fid[i].tagName=="SELECT")
      {
         if(fid[i].type.match(/multiple/i))
         {
            for(var ii=0; ii<fid[i].options.length; ii++)
            {
               if(fid[i].options[ii].selected) { params.push(encodeURIComponent(fid[i].name)+"="+encodeURIComponent(fid[i].options[ii].value)); }
            }
         }
         else { params.push(encodeURIComponent(fid[i].name)+"="+encodeURIComponent(fid[i].options[fid[i].selectedIndex].value)); }
      }
   }
   http.onreadystatechange=function()
   { 
     if(http.readyState==4)
     {
       if(http.status==200) { document.getElementById(divid).innerHTML=http.responseText; }
         else { alert("\n\nRequest error. "+http.status+" "+http.statusText); }
     }
   }
   http.open("POST",posturl,true);
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.send(params.join("&"));
} // function AjaxFormPost()
</script>

When that JavaScript is available on the web page, you're ready to implement the Ajax Form System.

The Form-Handling Script

The form-handling script needs to be one that can accept method POST web page form submissions. If it can do that, then it is compatible with this Ajax form system.

The location of the form-handling script is important.

Generally, the form-handling script needs to be installed at the same domain where the web page with the form is located. The restriction comes from Ajax security built into the browser.

Be that as it may, the form-handling script can be on another domain if the form-handling script sends certain specific HTTP headers to allow cross-site requests. The server side access control article at Mozilla has information about those headers.

If you don't have a form-handling script you can use for this Ajax for system, the Form Handler Software index page lists 3 to choose from.

Implementing the Web Page Form

This Ajax form system will not do form uploads. Other than that, use whatever web page form you want.

Preliminary

These 2 things need to be ready before the form can be implemented:

  1. The JavaScript needs to be in the web page source code or imported into the page.

  2. The form handling script needs to be installed and ready to go.

To Proceed

When the above 2 things are ready, the form can be implemented by doing these 3 things:

  1. Form tag id value —

    The form tag needs to have an id value so the JavaScript Ajax can find it. Example form tag with id value:

    <form id="ajax-form">
    

    The id value ajax-form is colored red because the value will be referred to when you modify the form submit button.

    (Form tag attributes action and method aren't required for this Ajax form system.)

  2. A div with id value for the form submission response —

    When Ajax gets a response from the form-handling script, the response is inserted into a div on the web page. The div must have an id value so Ajax can find it.

    The div with id value may be anywhere on the page. Optionally, the form may exist within that div to make the form disappear when the form-handling script's response is inserted.

    Here's an example div with id value:

    <div id="submission-response">
    Submission response will be published here.
    </div>
    

    The id value submission-response is colored green because the value will be referred to when you modify the form submit button.

    Note that the "Submission response will be published here" content is not required. The div may be empty.

    When the form-handling script's response is inserted, any content that previously existed within the div will be overwritten with the response.

    Here's an example div with id value that contains the form itself:

    <div id="submission-response">
    <form id="ajax-form">
    [form fields go here]
    </form>
    </div>
    

    When the form is within the div like that, the form will be overwritten with the form-handling script's response.

  3. The form submit button changes in two steps —

    Step A:
    The input type="submit" form tag needs to be changed to input type="button" so the form won't submit in the normal way (and can submit via Ajax when step "B" is done).

    Step B:
    The onclick attribute needs to be inserted into the input type="button" form tag with this value (you'll customize the value):

    onclick="AjaxFormPost('ajax-form','submission-response','/form-handler.php')">
    

    Customization notes for step "B":

    Replace ajax-form with the id value of your form tag.

    Replace submission-response with the id value of your div for the form-handling script's response.

    Replace /form-handler.php with the URL to the form-handling script that will process the form submission Ajax sends to it. Unless the form-handling script is on a different domain, use a relative URL so the protocol and domain restrictions are automatically complied with. (A relative URL is the URL with the protocol (http/https) and domain name removed.)

    Here's an example of an input type="button" form field.

    <input 
       type="button" 
       value="Tap Me" 
       onclick="AjaxFormPost('ajax-form','submission-response','/form-handler.php')">
    

Testing the Ajax Form System

Testing consists of using the form and verifying everything works as it should:

When the submit button is clicked, Ajax sends the form information to the form-handling script. When the form responds, the response is inserted into the web page.

When the submit button is clicked, Ajax sends the form information to the form-handling script. When the form responds, the response is inserted into the web page.

Because Ajax inserts the response into the page that contains the form, no new page load is required.

(This article first appeared in Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC