Submit Form to Multiple URLs With Ajax
It is possible to submit a form to two or more places with one click.
One destination URL is in the form tag's action attribute. The rest of the destination URLs are listed as a JavaScript variable.
When the form submit button is clicked, Ajax is used to first submit the form data to the URLs in the JavaScript variable. When those are done, the form is submitted to the URL specified in the form tag's action attribute.
Examples of use:
-
A subscription form submits to an email sending service. You want to also capture the form contents for your own database.
-
A member login script might not inform you whenever someone logs in. Ajax can submit to a PHP script that logs the information or sends you an email.
-
A payment form submits to PayPal or other payment gateway. Ajax can send the form information to a script before the browser is sent to the gateway. Perhaps also to another script for updating a file of email addresses authorized to download the product being purchased.
In each case, the Ajax submissions to the URLs in the JavaScript variable are done first. Then the form is submitted to it's action attribute URL.
The form tag's action attribute URL can be to any internet destination.
The Ajax destination URLs, however, are limited to the same protocol and domain where the form is being used.
That is, unless you control the external domain and allow Ajax to interact with the domain's software. See Cross-Domain Ajax That Works (When You Let It) for information about how to allow it to happen.
Implementing Multiple-URLs Form Submission
Enabling your form with this functionality requires two steps, (i) modifying your form and (ii) installing the JavaScript.
Step 1, Modifying Your Form
Two things need to be done to your form:
-
The form tag needs to have an id value.
-
And one of the following needs to be done (not both, just one or the other):
-
Either insert
onsubmit="return MultiURL_ProcessInformation()"
into your form's form tag.
-
Or insert
onclick="return MultiURL_ProcessInformation()"
into your form's submit button tag.
-
Note:
If you use the HTML5 required
attribute in your forms, be aware of this fact: When the submit button field has an onclick()
attribute, it nullifies any required
attributes of other form fields.
The onsubmit()
attribute in the form
tag can be used. It won't cancel required
attributes.
But onclick()
and required
attributes don't play nice together.
Step 2, Installing the JavaScript
The JavaScript below needs to be on the page or imported into the page. Two places need to be customized. Notes follow.
<script> /* Multiple-URLs Form Submission Version 1.0 November 6, 2016 Will Bontrager Software LLC https://www.willmaster.com/ Copyright 2016 Will Bontrager Software LLC This software is provided "AS IS," without any warranty of any kind, without even any implied warranty such as merchantability or fitness for a particular purpose. Will Bontrager Software LLC grants you a royalty free license to use or modify this software provided this notice appears on all copies. */ /* Customization. Two places. */ var MultiURL_FormTagIdValue = "multiple-destinations-form"; var MultiURL_ListOfURLs = Array("/script1.php", "/script2.php"); /* End of customization. */ var MultiURL_SubmittedCount = 0; function MultiURL_ObtainHTTPconnection() { try { http = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { http = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { try { http = new XMLHttpRequest(); } catch (e3) { http = false; } } } return http; } // function MultiURL_ObtainHTTPconnection() function MultiURL_ProcessInformation() { var inputList = new Object(); var form = document.getElementById(MultiURL_FormTagIdValue); var formlen = form.length; for( var i=0; i<formlen; i++ ) { if( ! form[i].name || form[i].name.length < 1 ) { continue; } if( form[i].type == "select-multiple" ) { var ti = form[i].options.length; for( var ii=0; ii<ti; ii++ ) { if( form[i].options[ii].selected ) { inputList[form[i].name+"\t"+i+"."+ii] = form[i].type+"\t"+form[i].options[ii].value; } } } else { inputList[form[i].name+"\t"+i] = form[i].type+"\t"+form[i].value; } } var params = new Array(); for (var id in inputList) { if (inputList.hasOwnProperty(id)) { var ta = id.split(/\t/); var key = ta[0]; ta = inputList[id].split(/\t/); var val = ta[1]; params.push(encodeURIComponent(key)+"="+encodeURIComponent(val)); } } var inputList = Object(); var data = params.join("&"); var params = Array(); var URLmethod = form.method.match(/get/i) ? "GET" : "POST"; var URLappend = ""; if( URLmethod == "GET" ) { URLappend = "?" + data; data = ""; } var URLsLen = MultiURL_ListOfURLs.length; for( var i=0; i<URLsLen; i++ ) { var http = MultiURL_ObtainHTTPconnection(); if(! http) { alert("Can't get HTTP connection for form submission."); MultiURL_SubmittedCount++; continue; } http.onreadystatechange = function() { MultiURL_ProcessInformationResponse(http); } http.open(URLmethod,MultiURL_ListOfURLs[i]+URLappend,true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.send(data); } if( MultiURL_SubmittedCount >= MultiURL_ListOfURLs.length ) { document.getElementById(MultiURL_FormTagIdValue).submit(); } else { return false; } } // MultiURL_ProcessInformation() function MultiURL_ProcessInformationResponse(http) { if(http.readyState == 4) { MultiURL_SubmittedCount++; if( MultiURL_SubmittedCount >= MultiURL_ListOfURLs.length ) { document.getElementById(MultiURL_FormTagIdValue).submit(); } } } // function MultiURL_ProcessInformationResponse() </script>
Customization notes:
There are two places to customize, color coded for easy recognition. The customization area is immediately below the header containing the name, license, and copyright information.
-
The value of MultiURL_FormTagIdValue needs to be updated.
Change multiple-destinations-form to your form's form tag id value.
-
The value of MultiURL_ListOfURLs needs to be updated.
The value is an array of one or more URLs.
If all the URLs are to the same domain as the web page with the form, specify URIs instead of URLs. URIs are URLs minus the protocol and domain name. With a URI, the browser assumes the same protocol and domain (including subdomain, if applicable) as the form page — which is what Ajax needs. But if you are submitting to a web page at an external URL, then the URL must be specified, not the URI.
In the array, the URIs are in quotes. If more than one, the URIs are separated with a comma and optional space and are all on the same line.
The above script has two URIs in the array, /script1.php and /script2.php to illustrate how it's done.
Change the MultiURI_ListOfURIs values to specify your own URIs and/or URLs.
How It Works
When the form is submitted, the onsubmit
in the form tag or the onclick
in the submit button tag launches the JavaScript function for submitting the form information to the URLs listed in the MultiURL_ListOfURLs array.
Only after those are all submitted with Ajax does the JavaScript cause the regular form submission to occur.
To do it otherwise — to let the form submission happen before all the Ajax submissions are accomplished — could interfere with the Ajax and cause some or even all of its submissions to be abandoned.
This is a convenient way to submit to multiple destinations. However, as you can see, the more URLs the Ajax has to submit to, the longer the form submission will take.
(This article first appeared in Possibilities ezine.)
Will Bontrager