What is JavaScript ? How to set up a website in it ?

JavaScript is one of the most popular and highest-rated programming languages in the world till date. It populary pronounce as a JS. It best known for its simplicity, versatility, and platform independency.

It is a text-based scripting language used on both client-side and server-side to make the web pages dynamic and interactive.

A bit into history, in the olden days the working of simple websites such as message displayers and random calculators used to be so different.

The web page sends the data to the server, and all the logic and computation happens at the server, and then the server sends the data back to the client(browser), and the result gets displayed on the web page.

This, indeed, is hefty and time-consuming for very simple websites that hardly used any functionality, which slows down the performance of the website.

Javascript is created in those circumstances by “Brendan Eich”. Javascript is a language that runs on the browser and that adds functionality or behavior to our website.

The first thing a person should understand before knowing how to use Javascript to create a website is, indeed, what a website is. So here it goes,

What is a website?

A page that displays some content on any kind of browser is known as a web page. A web page is set up using a markup language, generally HTML(Hyper Text Markup Language).

A website is simply a collection of one or many web pages under a common domain name. There are two types of websites, static and dynamic.

Static vs Dynamic website

A website is called static if the data it displays is fixed and cannot be changed. Static websites contain text content and attached images, links to external sites, and no buttons, forms, or dynamic/interactive content.

But there are also a vast majority of websites that allow the user to change or manipulate the data displayed on the browser. They are called Dynamic/Responsive websites.

Calculators, Unit Convertors, Message displayers, etc are some simple examples of responsive websites. Much complex ones may include applications like online food order and delivery which allows the user to access the features only if he/she is authorized.

Components(HTML, CSS, Javascript)

Now let us understand exactly how these websites work. Generally, the data that we receive from the server consists of three types of files, HTML, CSS, and Javascript.

The HTML file is responsible for the structure of the website, whereas CSS is responsible for the style. And finally when we incorporate the Javascript files, then our website actually starts having behavior.

Basically, there are two parts/ so-called ends for every website which when put together forms a complete web application.

Briefly, front-end refers to the client-side or web design in the web industry. Back-end refers to the server-side.

These components(HTML, CSS, JS) refer to the front-end of the website. But Javascript can also be used on the server-side by using platforms like Node.js which use Javascript to build the backend of the website.

Simple Javascript – How to add?

Create an HTML file and open it using any text editor you choose(in my case, I use Atom), and add the “script” tags under the body block. This is where we are going to add our Javascript.

Add the following code inside the scriptlet tag – alert(“Hello world!”);

The code looks something like this-






Now let’s add some behaviour, let us store the data provided inside the dialogue box (say our name) inside a variable and use it to display a message with our name. For that add the following code inside the scriptlet tag-

var name = prompt(“What is your name”);

alert(“Hello ”+name+”!”);

Well, you can also put all your JavaScript code inside a file named app.js and simply add the following code to HTML file-

Setting up a simple website using Javascript- What will we build?

Hola! Now that we have seen how to add JS to a website, let us dive deep and set up a dynamic website using JS. The application that we are going to build is a simple online calculator performing basic operations of Addition, Subtraction, Multiplication, and Division.

Setting up the Backend requirements

For this, we are going to use Node.js, which is a platform for JavaScript, which holds a lot of excesses that require libraries that can easily be accessed from JavaScript programming for better use.

Node.js allows us to take JS out of the browser and allows it to interact directly with the hardware of the computer. Let us see how we can install it – Download the installer from node's.

choose the LTS version. Now run the installer(.msi file) and accept all the default options. Restart your computer.

Node Package Manager and Express framework for backend

Express is a very popular framework for Node that many people depend on, it reduces the code by almost 5-10 times. Also, many packages that are used in the Node also depend on Express to run.

NPM(Node Package Manager) is a package manager for external modules. NPM will be installed along with the node on our system.

Create a folder named Calculator with three files inside, index.html, style.css, and app.js.

Now, open the command prompt and navigate to the required directory, and follow these steps with explanation in parentheses-

Open the command prompt and run the command, “npm init” to initialize npm, and accept all default options.

Run the command “npm i express body-parser”, to install packages express and body-parser.

Open the project inside any text editor you choose.

Note: create a folder named “public” inside the project, and a folder “css” inside the public folder, and move style.css inside that folder.

HTML code

Here goes the code for index.html, this adds the structure for the calculator.



Calculator

Calculator













Add

Subtract

Multiply

Divide





CSS code

Here goes code for style.css which adds styling to the calculator-

h1 {

text-align: center;

color: green;

}

.formclass{

padding-top: 60px;

padding-bottom: 60px;

padding-right: 10px;

padding-left: 10px;

background-color: #A9A9A9;

text-align: center;

width: 20%;

margin: 0 auto;

border-radius: 50%;

}

label{

padding-bottom: 10px;

}

.textbox{

padding-top: 3px;

padding-bottom: 3px;

}

submitButton{

padding-top: 5px;

background-color: green;

color: white;

}

Code in brief

We created a form in our HTML code, consisting of two text fields to provide the input numbers, a button group of radio-buttons which allows us to choose the operator, and a submit button which submits the data.

Notice that the action is taken on the “/” route, and the method is “post”. This implies that a post request will be made to the home route once the user submits the form.

Javascript code

Add the following code in app.js to require the packages that we have already installed i.e., express and body-parser-

const express = require("express");

const bodyParser = require(“body-parser”);

const app = express();

app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static(‘public’));

Express by default serves only the HTML code, so we must explicitly tell it to serve the static files in our folder ‘public’, hence the last line.

Now, configure our app to connect to a server through a port, in this case, port 3000.

app.listen(3000,function(){

console.log(“Server started on post 3000”);

});

Now, run “node app.js” command in prompt. If we get the message we tried to log in code, then congrats, the server has been connected successfully. Press ctrl+c to stop the connection.

Here, we send the requests from the browser to the server, and the servers’ response is displayed on the browser. If we type URL https://localhost:3000/ on the browser, it sends the first request i.e., a get request to route “/”, this is where we need to display our index.html. Add the following code to send a response to the browser in case of a get request. “__dirname” gives the directory you currently are in.

app.get("/",function(request,response){ response.sendFile(__dirname+”/index.html”);

});

Observe that in our HTML code, the form takes action on the “/” route with the method post, it means once the form is submitted, a post request is sent to the home route “/” from the browser.

So add the following code to send a response from the server when a post request is initiated-

app.post("/",function(request,response){ var e1 = Number(request.body.element1);

var e2 = Number(request.body.element2);

//console.log(request.body.operator);

switch(request.body.operator)

{

case "add": result = e1+e2;

break;

case "subtract": result = e1-e2;

break;

case "multiply": result = e1*e2;

break;

case "divide": result = e1/e2;

break;

default: result = "error";

}

response.send(“

The result is: “+result+”

“);

});

body-parser gives us access to request elements. Ex: req.body.element1, here element1 is the value of the name attribute of the first input. similarly for others. response.send is used to send the response to the browser, we need to provide the required HTML inside quotes. switch statement a part of javascript syntax, used here instead of multiple if-else blocks for simplicity.

Hola, now go to the browser and give the address https://localhost:3000/ and see our website up and running. Don’t forget to connect to the server by “node app.js” in prompt before moving to the browser.

Real-world applications

We saw how to create a simple web application using Javascript. Remember that this is only beginning and you can always refer to the online documentation for syntax and other features.

You need to learn about Application Programming Interfaces and Databases to build real-world applications.

Database

In websites like blogs, if we observe, all the data of a session gets lost once we restart the server and start another session on the browser.

How to tackle this problem? Actually, this happens because once we restart the server, the data structures like arrays get set to their default value, completely erasing our data generated from the memory.

So we need a persistent way to store our data, and we achieve that, indeed, by using databases. A database is an organized collection of structured information, or data, typically stored electronically in a computer system.

A database is usually controlled by a database management system (DBMS). There are two types of databases, SQL and NoSQL. In SQL, the data is stored in the form of table records, whereas in the latter, it is stored as JSON objects.

The SQL database is known for its ability to establish relations between data, whereas NoSQL databases for their flexibility. You need to choose one based on the application’s requirements.

Application Programming Interfaces

An API is a software intermediary that allows two applications to talk to each other. In other words, an API is a messenger that delivers your request to the provider that you’re requesting it from and then delivers the response back to you.

Let us say, you are building a website that requires the current weather condition to display. How will you get the data everytime you run your application on the browser? Well.

you can request the data from a standard weather website with the help of its API and interpret the required lines, again from the documentation, in your code. An API defines functionalities that are independent of their respective implementations, which allows those implementations and definitions to vary without compromising each other.

Therefore, a good API makes it easier to develop a program by providing the building blocks. Deployment In the application we built, we need to explicitly turn on the server to get the app running and it only runs on our system i.e., localhost.

Instead, we can deploy our application to real-world servers which are always up and running so we get a link that we can share and our application runs on any computer/ system.

You can choose the server you want to deploy your application to and follow its documentation to finish the process.


Article Written by Sai Lipika You can Contact Us if you have any query or want to setup website using JavaScript.
What is JavaScript ? How to set up a website in it ? What is JavaScript ? How to set up a website in it ? Reviewed by brij rai on September 01, 2020 Rating: 5

No comments:

please don't add Enter any spam Link in The comment box.

Powered by Blogger.