AJAX (Asynchronous JavaScript and XML) is the art of exchanging data with a server, and updating parts of a web page – without reloading the whole page.
We have already post a blog which explains about submitting form without page refresh, but it was done by using PHP and jQuery only. Now we will show how you can do the same with ajax, PHP and jQuery.
For this you must have a database in MY-SQL . Here, we have database named “mydba” which consists of table named “form_element” with 5 fields viz. “id”, “name”, “email”, “password” and “contact”.
next we create a php page named “ajaxsubmit.php” where following steps were performed:
- We first establish connection with server .
- Selects database.
- Executes query.
- Closing connection with server.
HTML File: ajaxsubmit.html
Here, we create our form
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="css/refreshform.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<h2>Submit Form Using AJAX and jQuery</h2> <!-- Required div Starts Here -->
<div id="form">
<h3>Fill Your Information !</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<label>Password :</label>
<input id="password" type="password">
<label>Contact No :</label>
<input id="contact" type="text">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
PHP File: ajaxsubmit.php
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("mydba", $connection); // Selecting Database
//Fetching Values from URL
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
$contact2=$_POST['contact1'];
//Insert query
$query = mysql_query("insert into form_element(name, email, password, contact) values ('$name2', '$email2', '$password2','$contact2')");
echo "Form Submitted Succesfully";
mysql_close($connection); // Connection Closed
?>
jQuery File: script.js
jQuery file consist of ajax functionality.
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&email1='+ email + '&password1='+ password + '&contact1='+ contact;
if(name==''||email==''||password==''||contact=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
MY-SQL Code Segment:
Here is the My-SQL code for creating database and table.
CREATE DATABASE mydba;
CREATE TABLE form_element(
id int(10) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
contact varchar(255) NOT NULL,
PRIMARY KEY (id)
)
CSS File: style.css
@import "http://fonts.googleapis.com/css?family=Fauna+One|Muli";
#form {
background-color:#fff;
color:#123456;
box-shadow:0 1px 1px 1px #123456;
font-weight:400;
width:350px;
margin:50px 250px 0 35px;
float:left;
height:500px
}
#form div {
padding:10px 0 0 30px
}
h3 {
margin-top:0;
color:#fff;
background-color:#3C599B;
text-align:center;
width:100%;
height:50px;
padding-top:30px
}
#mainform {
width:960px;
margin:50px auto;
padding-top:20px;
font-family:'Fauna One',serif
}
input {
width:90%;
height:30px;
margin-top:10px;
border-radius:3px;
padding:2px;
box-shadow:0 1px 1px 0 #123456
}
input[type=button] {
background-color:#3C599B;
border:1px solid #fff;
font-family:'Fauna One',serif;
font-weight:700;
font-size:18px;
color:#fff
}
Conclusion:
We showed you Ajax implementation with PHP, just follow our codes or download zip file to use.
You may also like to read:
50 Replies to “Submit Form Using Ajax, PHP and jQuery”
hi..
problem is that ,how to get employee id which is not insert by us.it is auto generated ,id ant to use this id in another table as a foreign key so
how to get id and save in another table
use mysqli_insert_id()function its return current inserted id
use max() function
you cannot use max(), cause what if somewhere along the line you decide to delete one row.
The auto-increment and max() would not be the same.
Use insert
hi..
problem is that ,how to get employee id which is not insert by us.it is auto generated ,id ant to use this id in another table as a foreign key so
how to get id and save in another table
use a hidden with its value set to GET_[employeeID] then use jquery to get value via an ID, class etc.
use a hidden input with its value set to GET_[employeeID] then use jquery to get value via an ID, class etc.
success: function(result){
alert(result);
}
is result is parameter?if it is than from you call this function…
alert (result) show “form successfully submited..
sir plz verify this function.
thanks.
Thank you so much for looking in to it.
It has been updated now.
how can i add a input file to this form and the ajax script?
Hey there,
Great script, best one I have found out of many on the web.
I’ve added some custom vars & tables to the script but I am having one issue and it is beyond my understanding.
The added fields are radio buttons with the id reflecting to its respective variable. It posts to the database correctly, however it will post the same submission for all the radio button fields every time. Changing the data entered on all the text fields will submit into the database, but for some reason all my radio button fields are submitting the same thing every time; no variances on user selection.
Appreciate it!
Paste your code here I will review it and let you know about the proper solution…
Never (or rarely) has such a great, concise, and complete tutorial/example been given. And with such brevity. Kudos. You all get it and that’s rare. Perhaps you horizontally integrate into teaching/training/tutorials?
Thanks so much!!
Hello Casa,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Catch up new posts from here
Regards,
FormGet Team
Thanks so much! It’s very helpful for me.
Hello Yudnee,
Pleased with your response.
Keep reading our other posts for more knowledge and coding tricks.
Regards,
FormGet Team.
i created a form that has
name
email
comment.
i want to link it to my email,
please i need your help.
so that when they submit i can get it on my email.
thanks
Hello Abiodun,
Follow up this post : https://www.formget.com/send-an-email-on-form-submission-using-php/
That will help you for the same.
Regards,
FormGet Team.
how put image in this form
can any one help me:
i need edit and delete code in ajax
sir plz tell me,,, i have one registration page,, when i click on submit button,, i want that my information will get stored in database and also that same information will stored in another php page in a table,,,,,
tell me plzzz
your article was really helpful. thanks
Why don’t you just use .Serialize() instead of chaining all the values together ?
Is there any reason or you wanted to keep it as simple as possible ?
thankz
Hi Its really good and it helped me a lot.Thank you for having this wonderful codes and work.
This solution is prone to a SQL injection attack. Check out http://stackoverflow.com/questions/9053736/sql-injection-through-mysql-query.
Also you can simplify the code required to build up the POST request quite a bit with $(“#form”).serialize(). You don’t need to build up the dataString the way you do. See this article. http://stackoverflow.com/questions/21357801/submit-form-and-a-textarea-on-ajax-post
To make it work however, you have to ensure all your input fields have the “name” attribute. The “id” attribute won’t work.
Thanks for this article, it was a great starting point and very useful
i am using this script on multiple form but its only working on very first form please reply how to use this on multiple form.
try to add ‘/’ before url it will work for sure…
Thank you Very much
nice tutorial
simple n nice
Thanks a lot…
Hi.. I’ve been away from php but recently looking at it again. Code very concise and clear to follow, thanks
Just wondering how secure the code is to hackers.. can tyhis go into production as-is ?
Hi Raj,
Our script is secure to use. You can use it.
Thanks, And I want to edit and delete by ajax php
and onchange….Kindly help me friends
thanku so much its really clear cut code for understanding ..awesome
I am truly happy to glance at this weblog posts which contains plenty
of valuable facts, thanks for providing such data.
this is good.. far more than better
Wonderful beat ! I would like to apprentice while you amend your site, how could i subscribe for a blog site?
The account aided me a acceptable deal.
I had been tiny bit acquainted of this your broadcast provided bright
clear concept
First of all, thank you for this code, it was very helpful.
I have one weird problem however. The last value in the dataString is not added to my database. If I replace the last value in var dataString with second last value, than somehow the other value is not added. It is always the last one. Am I missing something to close the variable? I tried a lot of things but cannot get it to work. Hope I explained my problem clear for you.
Christiaan
thats great ideas thanks alot
This website is very useful for beginners thank for your good coding example
what is the name1 js file
it is database filed or what????
please reply
why got error in my page is:
undefind index $doctoename is same as $name2
code
$doctor_name=$_POST[‘txtDoctorName’];
in ajaxsubmit.php page
How link html and php file
Thank you so mutch for sharing very helpfull coding for me am using your code at my site
Niicely written & done my friend!
I’ve just started blogging recently and realised that many bloggers
merely rehash oold content but add very little of worth.
It’s fantasic tto see a beneficial write-up off some real value to your readers.
It is actually on my list of creteria I need to replicate
as a neww blogger. Reader engagement and mateial value are
king.
Many superb thoughts; you’ve most certainly manged to get on my list
of people tto watch!
Keep up the excellent work!
Cheers,
Wenona
Well done and written my friend!
I began blogging recently and realised many articles merely rehash old ideas but add very little
of value. It’s terrific to read an enlightening post of some true value to me,
aas a reader.
It’s on the list of factors I need tto emulate
as a new blogger. Visitor engagement and content quality are king.
Some great ideas; you’ve most ceftainly got on my list of sites to follow!
Continue the good work!
Cheers,
Orin
Nicely written & done!
I’ve just started writing a blog myself in the last few
days and realized that lot of booggers simply rehash old ideas
but add very little of value. It’s good to read a helpful write-up of
some actual value tto myself and your other followers.
It’s on my liust of factors I need to emulate as a new blogger.
Audience engagement and content quality are king.
Some fantastic ideas; you’ve definitely gott on my list of sites to watch!
Carry on the fantastic work!
Well done,
Guendolen