-
Submit forms with POST method using AJAX
Posted on March 1st, 2009 21 comments
AJAX (Asynchronous JavaScript And XML) is a keystone of Web 2.0 and is very useful in many aspects, because it offers the possibility to change the structure of the page (DOM). For instance, it makes possible sending a form in a website without having to reload the whole page (’asynchronously‘ is the magic word here). The data submitted is processed and may be saved in a database just like classic forms do, but the user can continue browsing during the process.AJAX forms are a must-have for any AJAXed website. They can be used for many, many purposes: for checking whether a username already exists in the database; for seamlessly sending registrations, feedback or comments; or even for creating a shoutbox or chat script.
I prepared a simple example of an AJAX-powered form which submits data using the POST method. You can see the demo here. Keep reading to see the necessary code to create such a form and how it works. Note that this code is reusable and therefore same code can be used with various forms! See the details further on.Two files are needed for the form to work:
- index.html
- do.php
You will see the JavaScript code is included within the head tags of index.html; if your project is complex you might also want to place the code in an external .js file and include it accordingly.
If you’ve read other posts of mine dealing with AJAX you should already know what the role of those two files is: index.html has the code of the form and the output DIV (and in this example, the AJAX script), while do.php has the PHP code which processes the submitted data in any way you want (usually, insert it to a MySQL database).
Let’s see the code:
index.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>AJAX Post form demo</title> <script type="text/javascript"> <!-- var divid = 'output'; var loadingmessage = 'Processing...'; function AJAX(){ var xmlHttp; try{ xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari return xmlHttp; } catch (e){ try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer return xmlHttp; } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); return xmlHttp; } catch (e){ alert("Your browser does not support AJAX!"); return false; } } } } function formget(f, url) { var poststr = getFormValues(f); postData(url, poststr); } function postData(url, parameters){ var xmlHttp = AJAX(); xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){ document.getElementById(divid).innerHTML=loadingmessage; } if (xmlHttp.readyState == 4) { document.getElementById(divid).innerHTML=xmlHttp.responseText; } } xmlHttp.open("POST", url, true); xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlHttp.setRequestHeader("Content-length", parameters.length); xmlHttp.setRequestHeader("Connection", "close"); xmlHttp.send(parameters); } function getFormValues(fobj) { var str = ""; var valueArr = null; var val = ""; var cmd = ""; for(var i = 0;i < fobj.elements.length;i++) { switch(fobj.elements[i].type) { case "text": str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&"; break; case "textarea": str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&"; break; case "select-one": str += fobj.elements[i].name + "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&"; break; } } str = str.substr(0,(str.length - 1)); return str; } //--></script> </head> <body style="text-align: center;"> <div id="wrapper" style="position: relative; top: 50px;"><form id="aForm"> Please insert data in the fields below for trying the demo. Submitted data needn't be real; it is not stored anyway. <br /><br /> <label for="name" style="font-weight: bold;">Name: </label><input id="name" type="text" name="name" size="20"> <br /><br /> <label for="email" style="font-weight: bold;">E-mail: </label><input id="email" type="text" name="email" size="20"> <br /><br /> <input type="button" name="Send" value="OK" onclick="javascript: formget(this.form, 'do.php');"> </form> <br /><br />****** SERVER RESPONSE ******<br /><br /><br /> <div id="output" style="color: blue;"> </div> </div> </body> </html>I will attempt to explain what each part of the code above is for… but without entering into too much detail, as I assume the reader has some knowledge of how AJAX and JavaScript work.
Firstly, there are two variables the value of which can be customised: divid value must be the id of the DIV where the confirmation message or response text will be displayed; loadingmessage is the text which will be displayed in the specified divid telling the user that the form is being processed.
Secondly comes the AJAX() function. Without this, the form is not AJAXed. Good news is, this function is always the same and you don’t really need to completely understand how does it work, but only what is it needed for. You should read this guide if you don’t even know what it’s for (learn the basics of AJAX!).
Function formget() is the first function which is run, as it is called when the user clicks on the form’s submit button. It allows two variables (f and url) the values of which are set in the onclick event of the submit button.
- f is the name of the form to be submitted. Its value should be this.form, unless you want to submit a different form or the submit button is not within the form tags.
- url is the path to the PHP file which will process the submitted data. In our example, assuming that this file is in the same folder as index.html, the value should be do.php or whatever other name you chose for the file.
So as you can see in the example code provided, the submit button onclick event looks like:
onclick="javascript: formget(this.form, 'do.php');"
Function postData() has two variables: url and parameters. Url is already explained above; parameters will have as value the string with the submitted data.
Finally there’s the function GetFormValues(). For most forms you don’t really need to modify anything here. This function essentially builds the string of variables and values to be passed to the PHP script with the POST method. For each type of form element (text area, drop down menu, etc.) it builds the string accordingly. Depending on what other types of elements you have in your form, you will have to add some lines of code here or their value will not be passed to the PHP script. The other action it does is to automatically retrieve all the elements in the form; so you don’t need to manually specify the id of each element to be passed in the string: the function does it for you.
(Note: alternatively, you can obtain the code above directly from the source code of the demo page.)
do.php
echo 'Your name is ' . $_POST['name'] . ' '; echo 'Your e-mail address is ' . $_POST['email'] . ' '; $str = "You submitted the form on %a on %b %d, %Y, %X - Time zone: %Z"; echo(gmstrftime($str,time())); ?>
The code above is just a sample; it is the one used in the demo. Obviously you can modify the code to suit your needs. It is here where you would write the code to save the submitted data to a database, for instance.
A useful note here: as I mentioned above, there’s a DIV in index.html where the PHP script response text will be displayed. What is this PHP response text? Well, this is all what is echoed (so the PHP code is not response text). If you echo nothing, then there won’t be response text and nothing will be shown in the DIV. You can echo a confirmation message, a timestamp, the submitted data for confirmation, etc.
If you assembled the code correctly in your server, you should have a page like the demo.
Final note
Phew, that was a long one…
To finish, let me say that when you try to adapt the code here provided to your page, it should work (as you can see in the demo) – but in some cases it might not. It happens so often, when programming, than something does not work (as expected, or at all!); then comes the time to debug the code. So be very patient! Try to find what is causing the problem and make the necessary modifications so that your site and the code work correctly together.
In my opinion, even when sometimes it can become tedious and frustrating, debugging is the BEST way to learn
Related posts:
- Performing MySQL queries with the help of AJAX
- AJAX add content to favourites script
- Saving multiple selections from drop down list to database
- The dark side of AJAX
- Custom data in EventList frontend event submission form
AJAX, Computers & programming, HTML, JavaScript, MySQL, PHP ajax, asynchronous, code, div, form, html, javascript, mysql, php, post, section, submit, web 2.0, xml21 responses to “Submit forms with POST method using AJAX”
-
Aleix March 5th, 2009 at 22:49
Updated the code, fixed problem arising because of if(xmlHttp.status == 200).
-
thank you very much,
now I am trying to implement your code on my site -
tooqybility July 14th, 2009 at 06:34
thanks a lot bro,
but i have problem when i post the ‘FILE’ type. How to post it, so i could use its element (like:name, size etc) at my proses class?
thanks again for your answer to my question.
-
Aleix July 15th, 2009 at 00:33
Hello Tooqy,
Unfortunately I am not familiarized with operations involving files, and I just know the very very basics of handling them with PHP; therefore I think I cannot answer your question, but perhaps a reader with more experience in the field can clarify it. It would be helpful, in any case, to know what the problem exactly is, and other information which could give us an insight of the issue.
Regards,
Aleix
PS: by the way, I’ve just tested and found a syntax error in the code above, will try to fix it in the next 24 hours (16.07.2009); perhaps that’s causing the issue.
-
Hello and thanks for your script.
Can’t get this to work with checkboxes. You mention in your post that one will have to add som code to get it to work with all kinds of elements. Any suggestions to what to be added to get it to work?
Thank you in advance.
-
This makes it works for checkboxes.
case “checkbox”:
if(fobj.elements[i].checked == true){
str += fobj.elements[i].name +
“=” + fobj.elements[i].value + “&”;
}
break; -
Hey Fred,
Thanks for your feedback and your contribution; sorry that I couldn’t answer before but I was away on holiday for three weeks.
See you around
Aleix
-
I tried the demo myself on my localhost but email doesn’t seem to come. and i had been working this method on another file of mine but it doesn’t seem to have any effect, would it be possible for u to help me, if so do lemme know.
Thank you
-
Hello,
My first suggestion would be you try it on a online server; perhaps it is a problem of the mail server itself or of your server configuration.
However, while the code provided works to me, I’ve never tried to use it for sending e-mails; the logic tells me it should work anyway because the AJAX script simply calls a conventional PHP script to be run.Aleix
-
@sinan August 24th, 2009 at 21:43
If you look carefully at the answer of Fredskronk you will see that he use “&” instead of “&”
I really don’t know what means “&” but You must change in the code
“&” with “&”
Tell me if it works
Regards -
Good point @sinan, thanks! Had completely overlooked that mistake in the code. The blog sometimes changes the & for $amp;, which is the entity for ampersand:
http://htmlhelp.com/reference/html40/entities/special.html
This produces, of course, flaws in the code (and headaches to me), and could very well be this caused the malfunction.
Fixed the three sections of the code where this mistake was present…
Regards
PS: If you still experience trouble, you may alternatively try using the source code of the demo, which seems to work without problems (should be the same, though).
-
I can’t get this to work with checkbox’s
I’ve added:
case “checkbox”:
if(fobj.elements[i].checked == true){
str += fobj.elements[i].name +
“=” + fobj.elements[i].value + “&”;
}
break;My issue I get : Parse error: parse error, unexpected T_VARIABLE on the results page.
The line is : $user = $_POST['user'];
Any ideas ??
Thanks
-
Sorted it… my mistake TYPO !!
I need to call the web page and have the javascript run on page load.
How do I run this : onclick=”javascript: formget(this.form, ‘do.php’);”>
On page load ??
Thanks
-
Hello Tom,
If you want to run JS on page load, this should help:
http://javascript.about.com/library/blonload.htmGreetings
-
jadawl01 October 30th, 2009 at 00:13
Good tutorial
But dont know how to implement it in phpbb3 to send a quick reply in viewtopic and to have the new post appears without reloading the whole page -
Hi,
I am trying to implement this using a radio button. Is there a case for “radio” ?
-
Hi I’m really a newbie in js.
The script is just perfect but it doesn’t seems to work with textareasI’m studying the case “text” and case “checkbox” but i don’t find the model
I would really appreciate a quick answer with a standard “case textarea”
Thank you
-
Sorry about that. The script works just fine if you only change text to textarea
case “textarea”:
Silly me :d
-
chlorophyl November 18th, 2009 at 17:17
I am trying similar with multiple divs, but everytime when I access my control (drop down list which should be filled automatically from a mysql table) all code after this div seems to be removed (so also the second div). I am using IE 8. Do you know a solution?
Greetings.
-
Thank you SO MUCH for this blog post. I couldn’t figure out how the ajax knew which form to post until now. W3c, as well as many other tutorials, simply didn’t do a very good job of explaining how ajax knew which form to post and how the information was being packaged.
You rock,
Tony -
saravanan December 12th, 2009 at 11:04
Did any body have code for uploading files using php and ajax(post method). If have sent it it my mailid(vpsaran.85@gmail.com). I am in need of these urgently……..
Leave a reply
- index.html


