Ajax is a JavaScript based web development technology used for building asynchronous application. Ajax can send and receive date in the background (without page refreshing or redirecting). We need to use XMLHttpRequest object for working with ajax but jQuery library made it more easy to working with ajax by using jQuery.ajax, jQuery.get, jQuery.post methods.
In this post I have a simple html contact us form example that takes information(name, email, subject and message) from user. When user submit the form data send asynchronously to the server. PHP receives XMLHttpRequest request and process data from server side.
Live Demo
Download Source
HTML Markup
Let's take a look at html markup. We have a basic html contact us form
JavaScript and jQuery Code
This jQuery code used for submitting form with ajax request using jQuery.ajax method
PHP Code
We need to presses user submitted data from server side. This PHP code detects ajax request using HTTP_X_REQUESTED_WITH header request, looks for validation of data and send mail with PHP mail function.
In this post I have a simple html contact us form example that takes information(name, email, subject and message) from user. When user submit the form data send asynchronously to the server. PHP receives XMLHttpRequest request and process data from server side.
HTML Markup
Let's take a look at html markup. We have a basic html contact us form
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>HTML Form Submit with jQuery AJAX</title> </head> <body> <h1>Contact us</h1> <form action="" method="post"> <input type="text" name="name" /> <input type="mail" name="email" /> <input type="text" name="subject" /> <textarea name="message"></textarea> <button>Send Mail</button> </form> </body> </html>
JavaScript and jQuery Code
This jQuery code used for submitting form with ajax request using jQuery.ajax method
<!-- import jQuery library --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var form = $('#form'); // contact form var submit = $('#submit'); // submit button var alert = $('.alert'); // alert div for show alert message // form submit event form.on('submit', function(e) { e.preventDefault(); // prevent default form submit $.ajax({ url: '', // form action url type: 'POST', // form submit method get/post dataType: 'html', // request type html/json/xml data: form.serialize(), // serialize form data beforeSend: function() { alert.fadeOut(); submit.html('Sending....'); // change submit button text }, success: function(data) { alert.html(data).fadeIn(); // fade in response data form.trigger('reset'); // reset form submit.html('Send Email'); // reset submit button text }, error: function(e) { console.log(e) } }); }); }); </script>
PHP Code
We need to presses user submitted data from server side. This PHP code detects ajax request using HTTP_X_REQUESTED_WITH header request, looks for validation of data and send mail with PHP mail function.
# if request sent using HTTP_X_REQUESTED_WITH if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){ if (isset($_POST['name']) AND isset($_POST['email']) AND isset($_POST['subject']) AND isset($_POST['message'])) { $to = 'your@mail.id'; $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING); $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING); $sent = email($to, $email, $name, $subject, $message); if ($sent) { echo 'Message sent!'; } else { echo 'Message couldn\'t sent!'; } } else { echo 'All Fields are required'; } return; } /** * Email send with headers * * @return bool | void **/ function email($to, $from_mail, $from_name, $subject, $message){ $header = array(); $header[] = "MIME-Version: 1.0"; $header[] = "From: {$from_name}<{$from_mail}>"; /* Set message content type HTML*/ $header[] = "Content-type:text/html; charset=iso-8859-1"; $header[] = "Content-Transfer-Encoding: 7bit"; if( mail($to, $subject, $message, implode("\r\n", $header)) ) return true; }
First of all, great article! This has helped me a ton with AJAX. I was hoping you could elaborate on a part of this. I cannot figure out what is going on here.
ReplyDeletedata: form.serialize(),
...
"success: function(data) {
alert.html(data).fadeIn();"
I am having such a hard time with this concept, how is the alert being tied to the message being displayed?
Thanks in advance!
See api.jquery.com/serialize
DeleteHI, the form not working properly in Safari and Android, it send also if the fields are empty.
DeleteSorry, but I'm kinda confused on where to set the "To" email address. Am I missing something?
ReplyDeleteSorry, missed the field in the PHP code.
DeleteBut now I'm confused as to where I place this PHP code.
Nevermind, I figured it out once I dug through the source files.
Delete-I'm an idiot :P
i have same problem? for me the source is broken.. I am also stupid where do I put the PHP code??
DeleteHi, thanks for the nice article, its pretty cool. But I am facing a problem to use it in wordpress. It just shows "Sending..." when I click send email, not showing "message sent". Can anyone help me??
ReplyDeleteregards,
Biplob
I've the same problem!!! Don't know why!
DeleteI'm confused. There doesn't seem to be any actual validation in this form, so I added my own, but still no luck, it will send a blank email no matter what. So far I can't figure it out, but when it comes to php, jQuery and AJAX, I'm a n00b.
ReplyDeleteThanks for good article ; better for learners
ReplyDeleteHi! Great tutorial! Is there any way to apply this code using a div button as submit button? I tried different way but I didn't get lucky. Thanks!!
ReplyDeleteGreat stuff! Thanks!
ReplyDeleteBut I'm having problem using it all the way, after clicking the submit button.
Would be pleased if someone could take a look to see if I'm missing something.
http://www.kaoboj.se/test/form.html
This comment has been removed by the author.
ReplyDeleteHi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry.
DeleteThanks for your code, I still have the same problem than many people, i can't have the message sent correct after submitting the form, can you fix that?
ReplyDeletemany thanks
This comment has been removed by the author.
ReplyDeleteif( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
Deleteif (isset($_POST['name'])AND !empty($_POST['name'])AND isset($_POST['email']) AND !empty($_POST['email'])AND isset($_POST['subject']) AND !empty($_POST['subject'])AND isset($_POST['message'])AND !empty($_POST['message'])) {
if (preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', strtolower($_POST['email']))){
$to = 'your-email';
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$sent = email($to, $email, $name, $subject, $message);
if ($sent) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'That is not a valid e-mail address';
}
}
else {
echo 'All Fields are required';
}
return;
}
fix for 'required' and email control
Deletehii I have written all query in functions.php. i have written a function to update profile in functions.php.can I call a function in form action url
ReplyDelete
ReplyDeleteI agree with every aspect of it. Goodbye Obat jantung koroner
Mine message is not being delivered though it shows "Message sent!". Please help me out.
ReplyDeleteHi,
ReplyDeleteIs it possible to use multi form submit using your code?
Please help me.
Many Thanks
dịch vụ kế toán thuế tại ninh bình
ReplyDeletedịch vụ kế toán thuế tại vĩnh phúc
dịch vụ kế toán thuế tại hưng yên
dịch vụ kế toán thuế tại phú thọ
dịch vụ dọn dẹp sổ sách kế toán
dịch vụ dọn dẹp sổ sách kế toán tại thái bình
dịch vụ dọn dẹp sổ sách kế toán tại phú thọ
dịch vụ dọn dẹp sổ sách kế toán tại hưng yên
dịch vụ dọn dẹp sổ sách kế toán tại quận hải dương
dịch vụ dọn dẹp sổ sách kế toán tại hải phòng
dịch vụ dọn dẹp sổ sách kế toán tại quận thanh trì
dịch vụ dọn dẹp sổ sách kế toán tại quận hoàng mai
dịch vụ dọn dẹp sổ sách kế toán tại quận hai bà trưng
dịch vụ dọn dẹp sổ sách kế toán tại quận hoàn kiếm
dịch vụ dọn dẹp sổ sách kế toán tại quận từ liêm
dịch vụ dọn dẹp sổ sách kế toán tại quận ba đình
dịch vụ dọn dẹp sổ sách kế toán tại quận tây hồ
dịch vụ dọn dẹp sổ sách kế toán tại quận đống đa
dịch vụ dọn dẹp sổ sách kế toán tại bắc ninh
dịch vụ dọn dẹp sổ sách kế toán tại quận tphcm
dịch vụ dọn dẹp sổ sách kế toán tại quận cầu giấy
dịch vụ dọn dẹp sổ sách kế toán tại quận long biên
dịch vụ dọn dẹp sổ sách kế toán tại quận hà đông
dịch vụ dọn dẹp sổ sách kế toán tại quận thanh xuân
dich vu hoan thue gtgt
This comment has been removed by the author.
ReplyDeleteDapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule yang palsu.
ReplyDeleteSlimming capsule yang asli hanya ada di agen herbal tertentu seperti di distro herbal ini, kami merupakan agen herbal terbesar dan sudah di percaya di seluruh penjuru indonesia
Glucoberry merupakan Obat Jerawat Alami Paling Ampuh Dan Cepat, dengan serbuk alami dari glutathione dan colagen dimana khaisatnya mampu untuk memberikan nutrisi pada kulit yang mengalami masalah. Seperti kulit kasar, kulit berminyak, kulit yang berjerawat, kulit yang mengalami penuaan, kerutan di kulit
ReplyDeleteI have read your blog its very attractive and impressive. I like it your blog.
ReplyDeletePHP Training in chennai | PHP Training Course
PHP Training in chennai | Online PHP Course
Interesting Article
ReplyDeleteJQuery Online Training | Javascript Online Training
Wow. This really made my day. Thanks a lot!
JavaScript Training Courses | Javascript Online Training
nice
ReplyDeletei'm using jquery latest version, but it's not working, when i'm using jquery old version like 1.8.1 or older, it's work normally.
ReplyDeleteand my question is, how to use ajax works normally with jquery latest version?
sorry for bad english
obat jerawat alami
ReplyDeleteThis is one of the cult game now, a lot of people enjoy playing them . Also you can refer to the game :
ReplyDeleteanimal jam 2 | five nights at freddys 2 | hotmail login
thank you for sharing information
ReplyDeletefree online movie
hair growth faster
Tips Money Saving
Mais importante ainda, esses números de usuários também colocariam o Gmail na frente do hotmail.com entrar, executado pela Microsoft, tornando o Gmail o serviço de email mais usado no mundo. Em julho de 2011, a Microsoft disse que o hotmail.com entrar tinha 360 milhões de usuários. A empresa ainda não oferece uma atualização desde então.
ReplyDelete