Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryWebsite Development and Maintenance

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!

Submit Any Form Via Ajax

Recently, I needed to use Ajax to send form information to a script on a server.

The form fields were unpredictable. Sometimes there may have been an email field and sometimes not, for example. Sometimes the form had dozens of fields to submit, sometimes only a few.

Further, there were some form fields that should not be sent to the script (fields used for determining the content of other fields, like math formulas).

The requirement led me to create a simple JavaScript function for submitting a form via Ajax — without knowing in advance what the form fields would be.

What is Ajax?

Ajax is a tool programmed with JavaScript. The tool is used to send information to and get information from URLs. The way it connects to the URLs is with HTTP or HTTPS, the same methods that browsers use.

What makes Ajax special is that it can use HTTP/S to connect to other web pages or software on the internet from within the web page already loaded in the browser.

Thus, Ajax can be used to send form information to a PHP script on the server — without reloading the web page that has the form.

When Ajax is used to send form information to a server script, the form field names generally are specified within the Ajax source code. Yet when, as in the situation described above, the form fields are not known ahead of time and might change from page load to page load, form field names can not be specified with acceptable accuracy.

Another way had to be found. That method is what this article is about.

The code and examples in this article proved a base upon which you may build your own application.

Items to Consider

The web page form tag needs an id value. And the Ajax needs to know what that id value is.

The Ajax also needs to know the location of the PHP script (or other software) on the server to submit the form information to.

Implementing the System

Two things need to be ready before the Ajax can be used:

  1. The Form

    The form tag needs an id value.

    The form's id value needs to pass as a legal JavaScript variable name. Thus, use only letters, numbers, and underscore characters for the id value, and do not begin the id value with a number.

    Example:

    <form id="my_form" ...
    
  2. A Script on the Server

    A script on the server is required, a script to submit the form to. (In this article, it is assumed to be a PHP script, although you might use a Perl CGI script or other software for processing form information. The Ajax method in this article should work with any server script or software that the form information needs to be submitted to.)

    If you do not yet have a script for the form, you can temporarily use this one:

    <?php echo 'Received:'.print_r($_POST,true); ?>
    

    (When this temporary script receives form information, it replies with "Received:" plus whatever form information it received from the Ajax.)

    Upload the above temporary script to your server as script.php and make a note of its URL.

At this point, you have a web page with a form and you have a script on the server for sending form information to.

The Ajax JavaScript

Now that you have the above two requirements in place, let's install the Ajax JavaScript. Here is the source code. Notes follow.

<script type="text/javascript">
function SubmitFormWithAjax()
{
   var http = new XMLHttpRequest();
   http.onreadystatechange = function()
   { 
      if(http.readyState == 4 && http.status == 200)
      {
            alert(http.responseText);
      }
   }
   http.open("POST","/php/script.php");
   http.send(new FormData(my_form));
}
</script>

Notes —

Do the following edits and then put the JavaScript in the web page source code with the form. The JavaScript can be placed anywhere. Immediately below the form would let the JavaScript and form code be in proximity to each other.

Here are the two required edits. (An optional edit is noted further below.)

  1. Replace /php/script.php with the location of the PHP script that the form information is to be submitted to.

  2. Replace my_form with the web page form tag's id value.

The page is now ready for testing. Give it a try.

After the initial testing, you may decide to do the last edit, the optional one. It would depend on what you are using this for and its requirements.

Optional edit — With the above code, the Ajax JavaScript spawns an alert box when the server script responds from the form submission.

For your implementation, you may wish something a bit different.

Perhaps you prefer a "your form has been received" message. Or code to prevent the form from being used again. Perhaps you want to update a database with stats related to the form user — their geographical location, for example.

Whatever custom change you wish to make, it can be done, so long as it is doable with JavaScript.

If you wish to change the behavior, do so at the alert(http.responseText); line of the source code. You can do none, one, or both of these edits:

  1. To remove the alert box, delete the alert(http.responseText); line of code.

  2. To customize what happens after the script on the server responds, put your custom code above or below the alert(http.responseText); line of code.

How to Limit What is Submitted to the Server Script

When the form information is submitted to the server script with the Ajax JavaScript, only the values of form fields with a name attribute are submitted. Example: name="email"

Form fields that do not have a name attribute are not submitted.

All form fields may have id values, or not, up to you. It is only the name attribute that determines if the field value is submitted.

This gives you nice control over which form fields are sent to the script on the server.

A Nice Tool

What you have now is a nice tool for using Ajax when submitting any HTML web page form. It can come in mighty handy when the form needs to be submitted without reloading the page or loading a different page.

(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