How to Create a JavaScript Application and host on XAMPP

by Aug 3, 2022IoT Cloud, IoT Continuous Integration

Introduction

In this tutorial, we will be discussing in detail on how to create a responsive form from scratch using HTML, JavaScript, and Bootstrap 5. We use HTML for structuring the webpage, Bootstrap for stylizing it, and JavaScript for making the form responsive. We will be using external JSON files for the data displayed in our form. Also, we would be hosting the webpage locally using XAMPP software.

File System for the Form

The first step to creating a webpage is to create a folder to store all the required files for our webpage. The file system for our web form would look as follows :

File System

So, in our file system, we have a folder for bootstrap named CSS, an HTML file, two JavaScript files, and two JSON files. We need to download bootstrap 5 to add the CSS file to our file system. You can download it by clicking here. After downloading it, extract the zipped folder and copy-paste just the CSS folder into the file system. Next, you need to download a jquery file for our webpage. You can download it from here. For this project, I have used jquery-2.1.4.

In the next sections, we will talk about the remaining files in detail.

HTML File

An HTML file is required for structuring our webpage. It is the foundation of our webpage. The HTML code for our project is as follows :

<html>
    <head>
        <title>STUDENT DETAILS FORM</title>
        <link rel="stylesheet" href="css/bootstrap.css">
    </head>
    <body>
        <div class="container-lg">
            <div class="text-center">
                <br>
                <h2>Student Details Form</h2>
                <p class="lead">Questions to ask? Fill out the form to contact us!</p>
            </div>
            <div class="row justify-content-center my-4">
                <div class="col-lg-6">
                    <form onSubmit="saveFile()" name="webform" class="mt-1 border p-5 pb-4 bg-light shadow" >
                        <div>
                            <label for="mylist1" class="form-label">Name of the Student:</label>
                                <select required id="mylist1" name="STUDENT" class="form-select">
                                    <option value="">--Name--</option>
                                </select>
                            <br>
                            <label for="mylist2" class="form-label">Roll Number:</label>
                            <select required id="mylist2" name="ROLL_NO" class="form-select">
                                <option value="">--Roll No--</option>
                            </select>
                            <br>
                            <label for="mylist3" class="form-label">State/UT:</label>
                            <select required id="mylist3" name="STATE" class="form-select">
                                <option value="">--State--</option>
                            </select>
                            <br>
                            <div class="mb-4 text-center">
                                <input type="Submit" value="Submit" name="Submit" class="btn btn-secondary">
                                <input type="Reset" value="Reset" name="Reset" class="btn btn-secondary">
                            </div>
                            <div class="mb-4 text-center">
                                <small>&copy; IoTEDU</small>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>     
    </body>
</html>
EDIT: Add the following two lines of code right after the body tag begins

This is the complete HTML code for the project. Now let us look in detail at each part of the code

The HTML code starts with a <html> tag and ends with a </html> tag. It has two parts – a head and a body. Now let us look at the head section.

<head> element

head section

The head section starts with the <head> tag and ends with the </head> tag. It usually contains metadata i.e data about the HTML document such as the document title. Metadata is usually not displayed.

We give the document title within the title tag as shown on line 3.

Next comes the link tag. The link tag connects our HTML to an external file, usually a CSS file. So here we are using the link tag to connect to our bootstrap file. The link tag consists of an attribute called rel. The rel attribute specifies the relationship between our HTML document and the external file. So here, we give it as a “stylesheet”. Next, we use the href attribute to specify the path of the CSS file. Since the folder is within our file system, we don’t need to give its entire path. We need the bootstrap.css file for our project, so we can give the path as css/bootstrap.css.

Now, let us look at the body section.

<body> element

The body section starts with the <body> tag and ends with the </body> tag. It consists of all contents in our HTML page i.e headings, paragraphs, images, etc.

We use the script tag to connect our HTML document to our external JavaScript files. The type attribute specifies the type of the file, which here is a JavaScript file. The src attribute is used to give the path of our JS files. As our files are in the file system itself, just the name of the file along with the .js extension would suffice. We would be looking at the contents of our index.js file in detail in the coming section.

Subsequently, we start with the main content of our webpage using a <div> tag. The div tag is used to define a section of our webpage. This container would be used for the heading of our form. The div tag consists of a class attribute. We can use the class attribute to stylize the content within the div container. Here, we use a class called container-lg. It is a predefined class in bootstrap and we use it to set the size of our container. Following this, we start another div tag with the class text-center.

This class aligns with the heading at the center of the page. Next, we add the <br> tag for a line break. Since there is no content for the <br> tag, we don’t need to use a closing tag i.e it’s a self-closing tag. Following this, we type the heading within the <h2> tag. HTML provides us with heading sizes ranging from <h1> to <h6>. Next, we use a paragraph element <p> to write some text underneath the heading. We use the lead class to add some emphasis to the text. Finally, we close the container using the </div> tag.

<form> element

Next, we start with the contents of our form. We need to create a div container for our form. We use the class row justify-content-center my-4 to center-align the content and add some padding to the top and bottom. Then in the next div container, we specify the class as col-lg-6. It is used to specify the size of a column and stands for column large.

Following this, we start our form using the <form> tag. We use the onSubmit attribute to define the action taken on submitting the form. So, we call a function called saveFile() (which will be discussed in the JS section). Next, set the name of the form as “webform”. We have used the class mt-1 border p-5 pb-4 bg-light shadow to add padding and define the boundaries of our form.

Drop-down menus

We will be using drop-down menus in our form. The first drop-down menu is for choosing the name of the student. Therefore, we use the label element for setting the label of the drop-down menu. The for attribute is used to link the label to the id of the dropdown menu. The id of the first drop-down menu is mylist1. We use the form-label class for the label tag. The <select> tag is used to create a dropdown list. We use the required keyword to specify that an option must be selected before submitting the form. We set the id as mylist1 and the name as STUDENT for the drop-down list. Also, to stylize our form, we use the bootstrap class form-select.

Following this, we use the <option> tag to define the options. We need to create a default option, so we keep the value attribute blank to create one. By doing so, the user will have to choose an option before submitting the form (can’t submit the form with the default option).

NOTE: We are not hardcoding the options, rather we are taking the option data from an external JSON file (discussed in later sections)

Similarly, we need to create two more drop-down menus – one for roll number and another for state/UT.

Submit and Reset Buttons

Following the creation of drop-down menus, we need to create two buttons – Submit and Reset. We create it using a <input> tag of type Submit. It creates a submit button that submits all the form data. The action taken is controlled by the function specified in the onSubmit attribute of the form tag (discussed earlier). Similarly, we use an input tag of type Reset to create a reset button. This button resets all the chosen options to the default ones. In order to stylize the buttons, we use the class btn btn-secondary.

Finally, at the end of the form, we specify the copyrights by using the &copy; character followed by the organization’s name.

JavaScript File

So, now that we have done going through our HTML file, let us look at the contents of the index.js file. The complete code is as follows:

$.getJSON('names.json', function(data) {

    var select = document.getElementById("mylist1")
    var select2 = document.getElementById("mylist2")
    for(var i = 0; i < data['mylist1'].length; i++){
       var option = document.createElement("OPTION"),
           txt = document.createTextNode(data['mylist1'][i]['name']);
       option.appendChild(txt);
       select.insertBefore(option,select.lastChild);
       
       var option2 = document.createElement("OPTION"),
           txt2 = document.createTextNode(data['mylist1'][i]['id']);
       option2.appendChild(txt2);
       select2.insertBefore(option2,select2.lastChild);
    

    }
});

$.getJSON('states.json', function(data) {

    var select3 = document.getElementById("mylist3")
    for(var i = 0; i < data['states'].length; i++){
       var option3 = document.createElement("OPTION"),
           txt3 = document.createTextNode(data['states'][i]['name']);
       option3.appendChild(txt3);
       select3.insertBefore(option3,select3.lastChild);
       
    }
});

let saveFile = () => {
    	
    // Get the data from each element on the form.
    const name = document.getElementById('mylist1');
    const rollno = document.getElementById('mylist2');
    const state = document.getElementById('mylist3');
            
    // This variable stores all the data.
    let data = 
        '\r NAME OF THE STUDENT: ' + name.value + ' \r\n ' + 
        'ROLL NUMBER: ' +rollno.value + ' \r\n ' + 
        'STATE/UT: ' + state.value + ' \r\n '; 
                        
    // Convert the text to BLOB.
    const textToBLOB = new Blob([data], { type: 'text/plain' });
    const sFileName = 'formData.txt';	   // The file to save the data.

    let newLink = document.createElement("a");
    newLink.download = sFileName;

    if (window.webkitURL != null) {
        newLink.href = window.webkitURL.createObjectURL(textToBLOB);
    }
    else {
        newLink.href = window.URL.createObjectURL(textToBLOB);
        newLink.style.display = "none";
        document.body.appendChild(newLink);
    }
    newLink.click(); 
}
    

Firstly, we are going to link our external JSON files to our HTML file.

Linking the JSON files

So, we use the getJSON function to get data from our JSON file. We have named the file names.json. So here, we are intending to get the student names as well as the roll numbers from the JSON file. We are taking the roll numbers from the id values and names from the name value given in our JSON file.

Note that the list is named as mylist1 within the names.json file. The contents of the JSON file are attached below for your reference.

So first, we create two variables select and select2, and assign them to our first and second drop-down menus through their unique id’s. For this purpose, we use document.getElementById() function.

Now, we will loop through the contents of the JSON file to add them one by one to our drop-down menu. A for loop is used for this purpose. We can get the length of the content by using data[‘mylist1’].length. Within the loop, we create the HTML option element using the document.createElement(“OPTION”) and assign it to a variable option.

Following this, we create a text node (for text to be given within the option element) using the document.createTextNode() function and give the names from the JSON file as its argument. We assign the text node to the variable txt.

After doing so, we need to append the text to our options. We use the .appendChild() function to append the text to our options. Following this, we use the .insertBefore() function to insert the text node before the reference node.

Similarly, we create the options for the roll number drop-down menu too. The JSON file contents are as follows:

JSON files for the Form

{
    "mylist1":[

        {
            "id":"1",
            "name":"James"
        },

        {
            "id":"2",
            "name":"Sarah"
        },

        {
            "id":"3",
            "name":"Nitish"
        },

        {
            "id":"4",
            "name":"Sam"
        },

        {
            "id":"5",
            "name":"Shweta"
        },

        {
            "id":"6",
            "name":"Mohit"
        },

        {
            "id":"7",
            "name":"Jacob"
        },

        {
            "id":"8",
            "name":"Aarthi"
        },

        {
            "id":"9",
            "name":"Clara"
        },

        {
            "id":"10",
            "name":"Mohan"
        }


    ]
}

For the third drop-down menu (states/UT), we need to get data from our second JSON file named states.json

The code for it is the same as above, just we need to change the variable names and the id. The contents of the JSON file are attached below:

{
    "states":[

        {
            "id":"1",
            "name":"Andaman and Nicobar Islands"
        },

        {
            "id":"2",
            "name":"Andhra Pradesh"
        },

        {
            "id":"3",
            "name":"Arunachal Pradesh"
        },

        {
            "id":"4",
            "name":"Assam"
        },

        {
            "id":"5",
            "name":"Chandigarh"
        },

        {
            "id":"6",
            "name":"Chhattisgarh"
        },

        {
            "id":"7",
            "name":"Dadra and Nagar Haveli"
        },

        {
            "id":"8",
            "name":"Daman and Diu"
        },

        {
            "id":"9",
            "name":"Delhi"
        },

        {
            "id":"10",
            "name":"Goa"
        },

        {
            "id":"11",
            "name":"Gujarat"
        },

        {
            "id":"12",
            "name":"Haryana"
        },

        {
            "id":"13",
            "name":"Himachal Pradesh"
        },

        {
            "id":"14",
            "name":"Jammu and Kashmir"
        },

        {
            "id":"15",
            "name":"Jharkhand"
        },

        {
            "id":"16",
            "name":"Kerala"
        },

        {
            "id":"17",
            "name":"Lakshadweep"
        },

        {
            "id":"18",
            "name":"Madhya Pradesh"
        },

        {
            "id":"19",
            "name":"Maharashtra"
        },

        {
            "id":"20",
            "name":"Manipur"
        },

        {
            "id":"21",
            "name":"Meghalaya"
        },

        {
            "id":"22",
            "name":"Mizoram"
        },

        {
            "id":"23",
            "name":"Nagaland"
        },

        {
            "id":"24",
            "name":"Odisha"
        },

        {
            "id":"25",
            "name":"Puducherry"
        },

        {
            "id":"26",
            "name":"Punjab"
        },

        {
            "id":"27",
            "name":"Rajasthan"
        },

        {
            "id":"28",
            "name":"Sikkim"
        },

        {
            "id":"29",
            "name":"Tamil Nadu"
        },

        {
            "id":"30",
            "name":"Telangana"
        },

        {
            "id":"31",
            "name":"Tripura"
        },

        {
            "id":"32",
            "name":"Uttar Pradesh"
        },

        {
            "id":"33",
            "name":"Uttarakhand"
        },

        {
            "id":"34",
            "name":"West Bengal"
        },

        {
            "id":"35",
            "name":"Karnataka"
        },

        {
            "id":"36",
            "name":"Bihar"
        }

        
    ]
}

Next, we will look at the functions used in our form for submitting the data

Functions for the form data

In the earlier section, we discussed about the onSubmit attribute and the saveFile() function used for it. The objective of using this function is to download the form data as a text file locally. Now, let us look at the contents of this function.

Firstly, we get the data from our drop-down menus using their id’s as argument for the document.getElementById() function. We assign this data to three variables – name, rollno, and state.

Next, we store the form data that needs to be downloaded in a variable called data.

Next, we convert this text into a blob using Blob() function and assign it to a const textToBLOB. The value of a constant can’t be changed later. Next, we initialize another const sFileName as formData.txt.

Following this, we create an anchor element using .createElement() function. We would be downloading the data in a text file named formData.txt. The anchor element has an attribute named href which defines the link’s destination. Using an if-else loop, we assign the link of our data in blob format to the href attribute. Finally, on clicking the submit option in our form, the form data entered by the user will be downloaded as a text file to our system.

Hosting our Form locally using XAMPP

So, we have completed the coding part of our web form. Next, let us host it locally. We will be hosting it using the XAMPP software. You can download the software from here. After downloading, we need to follow a few steps to locally host our website. Firstly, locate a folder named htdocs in the xampp folder.

We need to copy and paste our file system into the htdocs folder. Next, open the XAMPP control panel and start the Apache module.

Next, open a browser preferably Google Chrome. Now, we need to type in the path of our file system. We do it in the following manner

eg. http://localhost/webpage/g_form.html

The name of the filesystem is webpage and the name of the HTML file is g_form. So we need to type in http://localhost/ followed by the name of our file system and the name of our HTML document. Do not forget to type in the .html extension. The end product would look as follows:

Conclusion

We have successfully created our responsive form using HTML, JS, and Bootstrap 5. We have seen how to get data from an external JSON file by linking it to our HTML. Also, we have seen how to host it locally using XAMPP software

Hope that this tutorial was informative and worth your time.

Happy Learning!

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Creating REST API CRUD with Node.js, Express and MongoDB

Creating REST API CRUD with Node.js, Express and MongoDB

In our previous blog, we explored the fundamentals of creating a REST API with in-memory CRUD operations using Node.js and Express. Now, we're taking a significant step forward by integrating our product data with a database. This transition is pivotal for achieving...

How to create REST API using Node.js and Express?

How to create REST API using Node.js and Express?

In the vast landscape of web development, creating a robust API is a fundamental skill. APIs, or Application Programming Interfaces, serve as the communication bridge between different software applications. Today, we'll embark on a journey to build a simple blog API...

APIs Vs. Microservices: What is the difference?

APIs Vs. Microservices: What is the difference?

You've probably heard two extravagant terms thrown around when discussing software design and integrations: APIs and microservices. Both topics are important in web application development and design nowadays, and their applications overlap. In this article, we will...

Understanding Salesforce IoT and Its Importance

Understanding Salesforce IoT and Its Importance

In this post, we are going to discuss Salesforce IoT. All across the globe, people are connecting to the Internet to access information, communicate with other people, and do business. But it's not just people that are using the Internet: objects use it too....

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....