DIY PHP and Bootstrap: Using Bootstrap Modal Box to Receive Input From User

Updated on May 8, 2018
timothy-malche profile image

Timothy is an enthusiast programmer and loves developing websites. He is expert in HTML, CSS, JavaScript, PHP, C#, and ASP[dot]NET.

1. Introduction

Bootstrap modal box is a window that pops up when user perform action such as button click. It works much like JavaScript alert box but is more advanced in features. It can be used to display either a simple message or to perform more complex operation such as receiving input from user.

Bootstrap modal box has three parts as shown in following figure:

Parts of Bootstrap Modal Box
Parts of Bootstrap Modal Box
  • Header part of Modal Box is used to display title or caption of the box.
  • Body part is a place where message or user interface is defined.
  • Footer part contains buttons to perform actions such as to submit form, save data or simply close it.

Now let’s begin our journey of creating the Modal Box. Please include Bootstrap library to your page. If you don’t know how to than please follow the link given in introduction section in my tutorial at https://hubpages.com/technology/How-to-control-values-displayed-in-one-HTML-Dropdown-List-with-the-other-using-simple-JavaScript.

2. Create the Modal Box

In this section we will create the modal box. Our modal box is very simple. As for now it contain only two fields one for accepting user’s full name and other for e-mail. I am not covering much in this tutorial as it’s just the starting of the series. My modal box also contain two buttons, for submitting form and for closing the modal box if user wish to.

The logic for submit button is implemented using JavaScript in the HTML file itself, and the close button uses attribute data-dismiss="modal" which internally fires event handler to close the modal box whenever the button is clicked.

Code for Bootstrap Modal Box
Code for Bootstrap Modal Box
<div class="modal fade" id="modalContactForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header text-center">
                <h2 class="modal-title font-weight-bold">Bootstrap Modal Form</h2>
            </div>
            <div class="modal-body mx-3">
                <div class="md-form mb-5">
                    <i class="fa fa-user prefix grey-text"></i>
					<label data-error="wrong" data-success="right" for="fname">Full Name:</label>
                    <input type="text" id="fname" class="form-control validate">
                </div>

                <div class="md-form mb-5">
                    <i class="fa fa-envelope prefix grey-text"></i>
					<label data-error="wrong" data-success="right" for="email">e-Mail:</label>
                    <input type="email" id="email" class="form-control validate">
                 </div>

            </div>
            <div class="modal-footer d-flex justify-content-center">
                <button id="send" class="btn btn-info">Submit <i class="fa fa-paper-plane-o ml-1"></i></button>
				<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

3. Launch the modal box

After the modal box is defined, we need a button to launch it so that it may appear to the user.

 <a href="" class="btn btn-success" data-toggle="modal" data-target="#modalContactForm">Launch Modal Contact Form</a>

4. Create section to display user’s submitted data

The data which user enters in the text boxes will be submitted to PHP page on the webserver and the response of PHP file is received in JavaScript code to inform user that his information is submitted successfully. To display this response I have created a section right after the definition of modal box.

<div class="modal-body">
        <div id="result"></div>
</div>
Code to launch Modal Box and Display Result
Code to launch Modal Box and Display Result

The interface will look like following

First view of Page
First view of Page

And when user click the button, modal box will appear as illustrated in following figure

View of Modal Box
View of Modal Box

5. Add JavaScript Code

Finally we need to add JavaScript code to make our modal box work

JavaScript code for Modal Box Functionality
JavaScript code for Modal Box Functionality

Following points help you understand code:

  • The click event is attached to submit button using the id of form #modalContactForm and button’s class .btn-info.
  • Value from text boxes has been extracted by using their ids #fname and #email and stored in variables vfname and vemail.
  • After extracting the values, it is sent to PHP page in the parameters fname and email.
  • And finally the response to the user is displayed in the div having id #result.

<script type='text/javascript'>

	 $(document).ready(function(){
	 $('#modalContactForm').on('click', '.btn-info', function(e){
     var vfname = $('#fname').val();
	 var vemail = $('#email').val();
   
	
			$.post("result.php", 
               { 
                  fname:vfname,
				  email:vemail,
               },
			function(response,status){ 
             $("#result").html(response);
            
          });
		  
     $('#modalContactForm').modal('hide');
   });
   });
		
  </script>

6. Create PHP file

The PHP file is a place where user's information is received and processed. In this tutorial I am only displaying it using echo function. In my next article I’ll show you how to store it to database.

<?php
   if($_POST["fname"])
   {
      
        echo "<h4>Thank you for submission!<h4>";
		echo "<br>Your Name: <b>".$_POST["fname"]."</b>";
		echo "<br>Your e-mail: <b>".$_POST["email"]."</b>";
   }
?>

7. Result

Run the form, and submit values. The result is shown in following figures.

Form is Filled with Data
Form is Filled with Data
Data is submitted and result is processed
Data is submitted and result is processed

8. Task for you

Follow the links given below to discover more on Bootstrap Modal Box and styles you may apply

you may also like to read article on my favorite list of websites that teach you web development

Download

You can download the source code for this article here:

Is this article helpful?

See results

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)