jQuery AJAX form submit using twitter bootstrap modal

In this article we can see about submitting a form using twitter boostrap modal . Twitter bootstrap contains a modal which has responsive features and beautiful CSS styles.
Here we required two files:
» index.html
» process.php
Jquery form submit

Javascript and CSS files :

Include Jquery and Bootstrap files in index.html

<link href="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>

Form content :

Here modal is referred by div id “form-content” which is basically hidden while loading and the form is referred by class “contact”.

<div id="thanks"><p><a data-toggle="modal" href="#form-content" class="btn btn-primary">Contact us</a></p></div>
	<!-- model content -->	
	<div id="form-content" class="modal hide fade in" style="display: none; ">
	        <div class="modal-header">
	              <a class="close" data-dismiss="modal">×</a>
	              <h3>Contact us</h3>
	        </div>
		<div>
			<form class="contact">
			<fieldset>
		         <div class="modal-body">
		        	 <ul class="nav nav-list">
				<li class="nav-header">Name</li>
				<li><input class="input-xlarge" value=" krizna" type="text" name="name"></li>
				<li class="nav-header">Email</li>
				<li><input class="input-xlarge" value=" user@krizna.com" type="text" name="Email"></li>
				<li class="nav-header">Message</li>
				<li><textarea class="input-xlarge" name="sug" rows="3"> Thanks for the article and demo
				</textarea></li>
				</ul> 
		        </div>
			</fieldset>
			</form>
		</div>
	     <div class="modal-footer">
	         <button class="btn btn-success" id="submit">submit</button>
	         <a href="#" class="btn" data-dismiss="modal">Close</a>
  		</div>
	</div>

Jquery code :

The below code will submit the form to process.php file and shows the processed results in the “thanks” div .

<script>
 $(function() {
//twitter bootstrap script
	$("button#submit").click(function(){
	        $.ajax({
    		type: "POST",
		url: "process.php",
		data: $('form.contact').serialize(),
        	success: function(msg){
 	                $("#thanks").html(msg)
 		       	$("#form-content").modal('hide');	
 		        },
		error: function(){
			alert("failure");
			}
      		});
	});
});
</script>

» process.php

The below php code will get the values from the form for processing .

<?php
if (isset($_POST['name'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['Email']);
$sug = strip_tags($_POST['sug']);
echo "Name		=".$name."</br>";	
echo "Email		=".$email."</br>";	
echo "Message		=".$sug."</br>";	
echo "<span class="label label-info" >your message has been submitted .. Thanks you</span>";
}?>

» index.html Full code :

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>jQuery AJAX form submit using twitter bootstrap modal</title> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<link href="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet"> 
<script src="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h4>Demo Page</h4>
	<div id="thanks"><p><a data-toggle="modal" href="#form-content" class="btn btn-primary">Contact us</a></p></div>
	<!-- model content -->	
	<div id="form-content" class="modal hide fade in" style="display: none; ">
	        <div class="modal-header">
	              <a class="close" data-dismiss="modal">×</a>
	              <h3>Contact us</h3>
	        </div>
		<div>
			<form class="contact">
			<fieldset>
		         <div class="modal-body">
		        	 <ul class="nav nav-list">
				<li class="nav-header">Name</li>
				<li><input class="input-xlarge" value=" krizna" type="text" name="name"></li>
				<li class="nav-header">Email</li>
				<li><input class="input-xlarge" value=" user@krizna.com" type="text" name="Email"></li>
				<li class="nav-header">Message</li>
				<li><textarea class="input-xlarge" name="sug" rows="3"> Thanks for the article and demo
				</textarea></li>
				</ul> 
		        </div>
			</fieldset>
			</form>
		</div>
	     <div class="modal-footer">
	         <button class="btn btn-success" id="submit">submit</button>
	         <a href="#" class="btn" data-dismiss="modal">Close</a>
  		</div>
	</div>
 </div>
<script>
 $(function() {
//twitter bootstrap script
	$("button#submit").click(function(){
		   	$.ajax({
    		   	type: "POST",
			url: "process.php",
			data: $('form.contact').serialize(),
        		success: function(msg){
 	          		  $("#thanks").html(msg)
 		        	$("#form-content").modal('hide');	
 		        },
			error: function(){
				alert("failure");
				}
      			});
	});
});
</script>
</body>
</html>

53 Comments

  1. I have been looking around for a solution like this for hours. Muchly appreciated.
    How would you call the Ajax from a form to start off with and then get the Thanks message (succces) from the process.php to appear in the modal?

    • success: function(msg){
      $(“#thanks-msg-from-process”).html(msg)
      $(“#form-thanks”).modal(‘open’);
      }

      Get the results to id “thanks-msg-from-process” and show the modal

  2. I have been looking around for a solution like this for hours. Muchly appreciated.
    How would you call the Ajax from a form to start off with and then get the Thanks message (succces) from the process.php to appear in the modal?

  3. hi is there any way to call thanks message in same model box.. i have created my custom process.php. but not able call thanks message in same model box when i sumbit it’s hiding $(“#form-content”).modal(‘hide’);

    • Remove “thanks” div and add it before the form like below

      -------------------------


      and remove $(“#form-content”).modal(‘hide’); from the script

          • start with this simple validation plugin

            http://jqueryvalidation.org/documentation/

            Include these js files
            http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js
            http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js

            Example script

            $(‘.contact’).validate({ // initialize the plugin
            rules: {
            Email: {
            required: true,
            email: true
            },
            name: {
            required: true,
            minlength: 5
            }
            },
            submitHandler: function (form) { // for demo
            alert(‘valid form submitted’); // for demo
            return false; // for demo
            }
            });

            check this

            http://jsfiddle.net/VuPPy/

          • thanks.. this are helping me.. can i Validated empty fields .Here is the example html code


            Script

            $(‘#validationform’).validate({ // initialize the plugin

            rules: {

            Email: {

            required: true,

            email: true

            },

            name: {

            required: true,

            minlength: 5

            }

            },

            $(function() {

            //twitter bootstrap script

            $(“button#submit”).click(function(){

            $.ajax({

            type: “POST”,

            url: “habitusprocess.php”,

            data: $(‘form.contact’).serialize(),

            success: function(msg){

            $(“#thanks”).html(msg)

            },

            error: function(){

            alert(“failure”);

            }

            });

            });

            });


            html

            Name

            Phone

            Email

            PROJECT

            option01

            option02

            option03

            option04

            PLEASE SHARE SOME DETAILS ABOUT YOUR PROJECT REQUIREMENTS

            process.php

            <?php

            /* subject mail variable*/

            $emailsubject = 'INQUIRY';

            $webMaster = 'addyourname@gmail.com';

            $headers = 'From: user@yourdomain.com';

            /*gatherning data variable*/

            $name = $_POST['name'];

            $phone = $_POST['phone'];

            $emailid = $_POST['emailid'];

            $projecttype = $_POST['projecttype'];

            $details = $_POST['details'];

            $body = <<<EOD

            Name:

            $name

            ContactNumber:

            $phone

            Email:

            $emailid

            ProjectType:

            $projecttype

            Details:

            $details

            EOD;

            $headers = “From: $mailrn”;

            $headers .= “Content-type: text/htmlrn”;

            $success = mail($webMaster, $emailsubject, $body, $headers);

            /*html*/

            $theResults = <<<EOD

            THANK YOU

            EOD;

            echo “$theResults”;

            ?>

          • process.php

            <?php

            /* subject mail variable*/

            $emailsubject = 'INQUIRY';

            $webMaster = 'addyourname@gmail.com';

            $headers = 'From: user@yourdomain.com';

            /*gatherning data variable*/

            $name = $_POST['name'];

            $phone = $_POST['phone'];

            $emailid = $_POST['emailid'];

            $projecttype = $_POST['projecttype'];

            $details = $_POST['details'];

            $body = <<<EOD

            Name:

            $name

            ContactNumber:

            $phone

            Email:

            $emailid

            ProjectType:

            $projecttype

            Details:

            $details

            EOD;

            $headers = "From: $mailrn";

            $headers .= "Content-type: text/htmlrn";

            $success = mail($webMaster, $emailsubject, $body, $headers);

            /*html*/

            $theResults = <<<EOD

            THANK YOU

            EOD;

            echo "$theResults";

            ?>

          • kind of solution example code..

            html code
            ========================
            added a empty div inside modal-body

            ==================

            Script code

            added if statement

            ========================

            if($(“#name”).val()==”” ||$(“#phone”).val() ==”” || $(“#emailtype”).val()==””)
            $(“#ack”).html(“Username and Phone, Email are mandatory fields Please Enter”);
            else

            ==========================

            $(function() {

            //twitter bootstrap script

            $(“button#submit”).click(function(event){

            event.preventDefault();
            if($(“#name”).val()==”” ||$(“#phone”).val() ==”” || $(“#emailtype”).val()==””)
            $(“#ack”).html(“Username and Phone, Email are mandatory fields Please Enter”);
            else
            $.ajax({
            type: “POST”,
            url: “process.php”,
            data: $(‘form.contact’).serialize(),
            success: function(msg){
            $(“#thanks”).html(msg)
            },
            error: function(){
            alert(“failure”);
            }
            });

            });
            });

          • Thank you so much for this validation demo. I have been looking all over for an example just like this. You saved me.
            thanks

  4. Remove “thanks” div and add it before the form like below

    -------------------------


    and remove $(“#form-content”).modal(‘hide’); from the script

        • start with this simple validation plugin

          http://jqueryvalidation.org/documentation/

          Include these js files
          http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js
          http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js

          Example script

          $(‘.contact’).validate({ // initialize the plugin
          rules: {
          Email: {
          required: true,
          email: true
          },
          name: {
          required: true,
          minlength: 5
          }
          },
          submitHandler: function (form) { // for demo
          alert(‘valid form submitted’); // for demo
          return false; // for demo
          }
          });

          check this

          http://jsfiddle.net/VuPPy/

          • thanks.. this are helping me.. can i Validated empty fields .Here is the example html code


            Script

            $(‘#validationform’).validate({ // initialize the plugin

            rules: {

            Email: {

            required: true,

            email: true

            },

            name: {

            required: true,

            minlength: 5

            }

            },

            $(function() {

            //twitter bootstrap script

            $(“button#submit”).click(function(){

            $.ajax({

            type: “POST”,

            url: “habitusprocess.php”,

            data: $(‘form.contact’).serialize(),

            success: function(msg){

            $(“#thanks”).html(msg)

            },

            error: function(){

            alert(“failure”);

            }

            });

            });

            });


            html

            Name

            Phone

            Email

            PROJECT

            option01

            option02

            option03

            option04

            PLEASE SHARE SOME DETAILS ABOUT YOUR PROJECT REQUIREMENTS

            process.php

            <?php

            /* subject mail variable*/

            $emailsubject = 'INQUIRY';

            $webMaster = 'addyourname@gmail.com';

            $headers = 'From: user@yourdomain.com';

            /*gatherning data variable*/

            $name = $_POST['name'];

            $phone = $_POST['phone'];

            $emailid = $_POST['emailid'];

            $projecttype = $_POST['projecttype'];

            $details = $_POST['details'];

            $body = <<<EOD

            Name:

            $name

            ContactNumber:

            $phone

            Email:

            $emailid

            ProjectType:

            $projecttype

            Details:

            $details

            EOD;

            $headers = “From: $mailrn”;

            $headers .= “Content-type: text/htmlrn”;

            $success = mail($webMaster, $emailsubject, $body, $headers);

            /*html*/

            $theResults = <<<EOD

            THANK YOU

            EOD;

            echo “$theResults”;

            ?>

          • process.php

            <?php

            /* subject mail variable*/

            $emailsubject = 'INQUIRY';

            $webMaster = 'addyourname@gmail.com';

            $headers = 'From: user@yourdomain.com';

            /*gatherning data variable*/

            $name = $_POST['name'];

            $phone = $_POST['phone'];

            $emailid = $_POST['emailid'];

            $projecttype = $_POST['projecttype'];

            $details = $_POST['details'];

            $body = <<<EOD

            Name:

            $name

            ContactNumber:

            $phone

            Email:

            $emailid

            ProjectType:

            $projecttype

            Details:

            $details

            EOD;

            $headers = "From: $mailrn";

            $headers .= "Content-type: text/htmlrn";

            $success = mail($webMaster, $emailsubject, $body, $headers);

            /*html*/

            $theResults = <<<EOD

            THANK YOU

            EOD;

            echo "$theResults";

            ?>

          • kind of solution example code..

            html code
            ========================
            added a empty div inside modal-body

            ==================

            Script code

            added if statement

            ========================

            if($(“#name”).val()==”” ||$(“#phone”).val() ==”” || $(“#emailtype”).val()==””)
            $(“#ack”).html(“Username and Phone, Email are mandatory fields Please Enter”);
            else

            ==========================

            $(function() {

            //twitter bootstrap script

            $(“button#submit”).click(function(event){

            event.preventDefault();
            if($(“#name”).val()==”” ||$(“#phone”).val() ==”” || $(“#emailtype”).val()==””)
            $(“#ack”).html(“Username and Phone, Email are mandatory fields Please Enter”);
            else
            $.ajax({
            type: “POST”,
            url: “process.php”,
            data: $(‘form.contact’).serialize(),
            success: function(msg){
            $(“#thanks”).html(msg)
            },
            error: function(){
            alert(“failure”);
            }
            });

            });
            });

          • Thank you so much for this validation demo. I have been looking all over for an example just like this. You saved me.
            thanks

  5. Hi Krisna. I send the data to a php controller and if I return an error I want to be able to display it in the same modal and hide when the controller returns a valid input. How can I do that?

  6. Hi Krisna. I send the data to a php controller and if I return an error I want to be able to display it in the same modal and hide when the controller returns a valid input. How can I do that?

  7. Great tutorial. But I’m having a problem. The JavaScript you’ve provided at the end of form is bypassing my validation. Any suggestions?

  8. Great tutorial. But I’m having a problem. The JavaScript you’ve provided at the end of form is bypassing my validation. Any suggestions?

  9. Is there a way to hide the submit button after a successful registration?
    I use a double opt-in signup and put the return messages from my signup script in the same modal just above the form.
    When I get a successful signup I show the message “Please go and check you email” and would like to remove/hide the submit button, otherwize if the click again they get a “This email is already registered” message.

  10. Is there a way to hide the submit button after a successful registration?
    I use a double opt-in signup and put the return messages from my signup script in the same modal just above the form.
    When I get a successful signup I show the message “Please go and check you email” and would like to remove/hide the submit button, otherwize if the click again they get a “This email is already registered” message.

  11. Hi. If I update to the latest version of bootstrap, the modal popup no longer appears. Any thoughts on what I need to do will be appreciated. Thanks

  12. Hi. If I update to the latest version of bootstrap, the modal popup no longer appears. Any thoughts on what I need to do will be appreciated. Thanks

  13. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get got an edginess over that you wish
    be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this hike.

1 Trackback / Pingback

  1. modal box login form ajax jquery php - Tech Magazine

Leave a Reply

Your email address will not be published.


*