Monday, June 10, 2013

jQuery validation : Validate and submit a form without refreshing the page using PHP, jQuery and Bootstrap

The jQuery way of doing form submissions
Here's the jQuery way, which is made possible by AJAX (which stands for Asynchronous JavaScript and XML). AJAX is bascially the technology that makes it possible to exchange data with a server, and update parts of a web page – without reloading the whole page. jQuery includes the necessary functions to implement AJAX into your web application.

In the traditional method, when you click the submit, your browser will load process.php and it will jump from form.php to process.php.

With the jQuery/AJAX way, process.php becomes a background process which the web server will call on, and when you click on the "Submit" button, form.php pushes the data to process.php, but your browser will remain showing form.php. Once the process.php has done what it needs to, it will return to form.php some output to be displayed.

I call the jQuery validate method (make sure you have included the jquery validate plugin - download the script from jqueryvalidation.org) on my form #contact-form, and proceed to define what to validate.

Lastly, the submitHandler is what gets processed if the validation is successful. In this case, I'm doing an ajax post method, sending my form data to process.php, and get back any results as HTML data which will be displayed into #results.

Over at process.php, I'm simply printing out the data received to show you the information was sent and returned.

I have posted the complete source code and screen dump of final outcome. Feel free to use it. :)

Bootstrap Contact form 

Form built with Twitter Bootstrap
<style type="text/css">
label.valid {
width: 24px;
height: 24px;
background: url(../img/valid.png) center center no-repeat;
display: inline-block;
text-indent: -9999px;
}
label.error {
font-weight: bold;
padding: 2px 8px;
margin-top: 2px;
}
</style>
<div class="container-fluid">
<div class="row-fluid">
<div class="span9 offset3">
<form action="" id="contact-form" class="form-horizontal" method="post">
<fieldset>
    <div class="control-group">
        <label class="control-label" for="name">Your Name</label>
        <div class="controls">
            <input type="text" class="input-xlarge" name="name" id="name">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="email">Email Address</label>
<div class="controls">
            <input type="text" class="input-xlarge" name="email" id="email">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="subject">Subject</label>
        <div class="controls">
            <input type="text" class="input-xlarge" name="subject" id="subject">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="message">Your Message</label>
        <div class="controls">
            <textarea class="input-xlarge" name="message" id="message" rows="3"></textarea>
        </div>
    </div>
    <div class="control-group">
        <div class="controls">
            <button type="submit" class="btn">Send Email</button>
        </div>
    </div>
</fieldset>
</form>
<!-- We will output the results from process.php here -->
<div id="results"></div>
</div>
</div>
</div>

Required jQuery/Javascript
$(document).ready(function() {
 $('#contact-form').validate({
  rules: {
   name: {
    minlength: 2,
    required: true
   },
   email: {
    required: true,
    email: true
   },
   subject: {
    minlength: 2,
    required: true
   },
   message: {
    minlength: 2,
    required: true
   }
  },
  highlight: function(element) {
   $(element).closest('.control-group').removeClass('success').addClass('error');
  },
  success: function(element) {
   element.text('OK!').addClass('valid').closest('.control-group').removeClass('error').addClass('success');
  },
  submitHandler: function(form) {
   // do other stuff for a valid form
   $.post('process.php', $("#contact-form").serialize(), function(data) {
    $("#contact-form").hide();
    $('#results').html(data);
   });
  }
 });
}); // end document.ready

PHP
//process.php
<?php
 print "Form submitted successfully: <br>Your name is <b>".$_POST['name']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>

Ref: http://www.askaboutphp.com/213/php-and-jquery-submit-a-form-without-refreshing-the-page.html

9 comments:

  1. Hello,
    I visited your blog.
    Congratulations for your work!! An interesting and nice blog!!
    Good luck with your blog!
    Greetings from Algarve, Portugal
    Paulo Gonçalves

    I invite you to visit my blog
    http://viajaredescobrir.blogspot.com

    ReplyDelete
  2. nice work dude.. ive been looking for this.. thank you for sharing

    ReplyDelete
  3. great tutorial could you pliz add a download link.thanx in advace

    ReplyDelete
    Replies
    1. if you copy and paste the above source codes with correct file names, it will work automatically.
      Hope this will work as download for you. :)

      Delete
  4. Hello Bro,
    I copied your code and the form worked perfectly fine..
    i want to use it in my wordpress. is there anyway to use this form in wordpress without using plugin?
    Please help...

    ReplyDelete
    Replies
    1. It is very much possible. I have done it long time ago. I don't have source left. But what i did was place the codes (html, jquery) in the right place. Do exactly same as you do in PHP and it will work. You don't need to do any thing special.

      Delete
    2. well, the only thing i didnt understand is...when i press submit button...the form wont send...and process.php is not in active state..

      Delete