Showing posts with label advanced javascript. Show all posts
Showing posts with label advanced javascript. Show all posts

Tuesday, October 27, 2015

A simple Node.js HTTP Server

In this post, I am going to show, how to create a simple Node.js HTTP server.

I took the example of creating the following:

1. A HTML that auto submits geolocation latitudes and longitudes to a Node.js HTTP Server.
2. A js file that creates HTTP Server using http module in Node.js.

The server:

In Node.js we can create a simple HTTP Server using http module.

we can import http module like this:

var http = require('http');

we can create server using the following:

we have to pass a simple callback to the 'createServer'.

http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type':'text/html'});
response.write("<p style='color:red;font-size:30px'>This is a Node JS HTTP Server</p>");
response.end();
});

Using writeHead one can set status and content type.
Things we need to return to the client will be written in 'write'.
One has to definitely end the server using 'end', otherwise page loads and loads.

My complete server code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var http=require('http');
var url = require('url');
http.createServer(function (request, response) {
 response.writeHead(200, {'Content-Type':'text/html'});
 response.write("<p style='color:red;font-size:30px'>This is a Node JS HTTP Server</p>");
 var latitude = url.parse(request.url).query.split("&")[0].split("=")[1];
 var longitude = url.parse(request.url).query.split("&")[1].split("=")[1];
 response.write("<p style='color:Red; font-size:30px;'>Position's latitude is: "+latitude+"<br/>Position's longitude is: "+longitude+"</p>");
 console.log(latitude+" | "+longitude);
 response.write("<img src='https://maps.googleapis.com/maps/api/staticmap?center="+latitude+","+longitude+"&zoom=12&size=300x300&sensor=false'/>");
 response.end();
}).listen(3000);


I used a HTML form that finds latitude and longitude using geolocation API in javascript and auto submits a form in 3 seconds.

The form submits itself to the server for a response.

My HTML code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<html>
<script>
 navigator.geolocation.getCurrentPosition(function(positionVar) {
   var coordinates = positionVar.coords;
   var br = document.createElement("br");
   var inp1 = document.createElement("input");
   inp1.value="Latitude";
   inp1.disabled="disabled";
   inp1.backgroundColor="red";
   document.body.appendChild(inp1);
   var inp2 = document.createElement("input");
   inp2.value="Longitude";
   inp2.disabled="disabled";
   inp2.backgroundColor="red";
   document.body.appendChild(inp2);
   document.body.appendChild(br);
   var form1 = document.createElement("form");
   form1.action='http://localhost:3000/latitudesAndLongitudes';
   form1.method="get";
   form1.id="f1";
   document.body.appendChild(form1);
   var latitude = document.createElement("input");
   latitude.type="text";
   latitude.value=coordinates.latitude;
   latitude.name="latitude";
   form1.appendChild(latitude);
   var longitude = document.createElement("input");
   longitude.type="text";
   longitude.value=coordinates.longitude;
   longitude.name="longitude";
   form1.appendChild(longitude);
   form1.appendChild(br);
   var submit = document.createElement('input');
   submit.type="submit";
   submit.value="Click Here to navigate to the server";
   form1.appendChild(submit);
   setTimeout(function() {
    document.forms["f1"].submit();
   }, 3000);
  }, function (err) {
   throw err;
  });
</script>
</html>


This also can be simply written as :) :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<html>
<head>
<script>
function function1() {
 navigator.geolocation.getCurrentPosition(function(positionVar) {
   var coordinates = positionVar.coords;
   document.getElementById("id4Lat").value=coordinates.latitude;
   document.getElementById("id4Lng").value=coordinates.longitude;
   var f1 = document.getElementById("f1");
   setTimeout(function() {
    document.forms["f1"].submit();
   }, 3000);
  }, function (err) {
   throw err;
  });
 }
</script>
</head>
<body onload='function1();'>
<form action="http://localhost:3000/latitudesAndLongitudes" method="get" id="f1">
<input type="input" disabled="disabled"  value="Latitude"/>
<input type="input" disabled="disabled"  value="Longitude"/>
<br/>
<input type="input" name="latitude" id="id4Lat"/>
<input type="input" name="longitude" id="id4Lng"/>
<br/>
<input type="submit" value="Click Here else wait for 3 seconds"/>
</form>
</body>
</html>

Results I have got:

I have masked the latitude and longitude on purpose, one can view them fully.

My HTML page:



Once this shows up user can click the submit button there below in 3 seconds, else it auto submits.

I assigned an id to the form and I used this code to auto submit the form to the server.

Action attribute is assigned with server's path and I used get method.

document.forms['f1'].submit();

I used the above code in a setTimeout method callback to buy some delay (3 seconds in this case).

Used general geolocation API to retrieve the location's latitude and longitude.

Server returns this:



Since I used get method to submit the form, you can see the query string in the address bar in above image showing us the parameters.

In node, we can get query string using url module like this:

var url = require('url');
url.parse(request.url).query;

Node logs:



Geolocation API by default is not supported by Node.js

One would have to install it using npm like this:

npm install geolocation

Once installed one can import geolocation using:

var geolocation = require('geolocation');

And general callback goes as normal javascript geolocation call.

Code goes like this with geolocation module installed on node.js



1
2
3
4
5
6
7
var geolocation = require('geolocation');
geolocation.getCurrentPosition(function(positionVar) {
   var coordinates = positionVar.coords;
   //lats and lngs likewise
}, function(err) {
   throw err;
});


Please don't hesitate to drop in any suggestions, happy learning.

Tuesday, September 8, 2015

Creation of dynamic HTML Part II

In this post, I am about to write about the way of creating dynamic HTML using javascript using a JS function called createElement.

The process is pretty straight forward unlike the other dynamic HTML way where we dump HTML into innerHTML of a dummy tag.

Here we can create new tags entirely without using dummy tags.

Here is the HTML/JS code I've written.


1:  <html>  
2:  <head>  
3:  <script>  
4:  function function1()  
5:  {  
6:       var var1 = document.createElement("center");  
7:       var var2 = document.createElement("p");  
8:       var2.style.color="teal";  
9:       var2.style.fontSize="20px";  
10:       var2.innerHTML = "Dynamic HTML Paragraph";  
11:       var2.id="id1";  
12:       var var3 = document.createElement("button");  
13:       var3.textContent="Click here to delete the dynamic HTML";  
14:       var3.id="id2";  
15:       var3.onclick = function()   
16:       {  
17:            var var4 = confirm("You sure ?");  
18:            if(var4)  
19:            {  
20:                 var var5 = document.getElementById("id1");  
21:                 var5.parentNode.removeChild(var5);  
22:                 var var6 = document.getElementById("id2");  
23:                 var6.parentNode.removeChild(var6);  
24:            }  
25:       };  
26:       var1.appendChild(var2);  
27:       var1.appendChild(var3);  
28:       document.body.appendChild(var1);  
29:  }  
30:  </script>  
31:  </head>  
32:  <body onload="function1(); ">  
33:  <h3>Creation of dynamic HTML using javascript createElement (This is static ofcourse) &#9786</h3>  
34:  </body>  
35:  </html>  

In the above code in line number 33, I have written static HTML code.

In script tag I have written a function and called it onload of body.

In the function in line 4, I have took sort of a parent element "center" tag using createElement as in line 6.

I went ahead and created two more tags "p" and "button" using createElement.

Important part is that we have to attach these two elements to center tag.

I assumed center tag as a parent tag.

In turn I attached this center tag to body as in line 28.

I have also included onclick functionality for the button tag.

On clicking the button you will be asked if you want to delete. If we say Yes, it deletes both the p button tags created dynamically.

I used the code in lines 20-23 for deleting the tags.

I felt this is a very efficient way to create HTML tags in javascript as I am able to control almost everything of the tag in javascript, instead of writing HTML and dumping HTML as a string into innerHTML.

For instance if I wanted to control the color of the tag. I am first creating the element like

var var1 = document.createElement("p");
var1.innerHTML="P tag";
var1.style.color="lime";
var1.style.fontSize="20px";

I figured style's usage is like

we generally use

<p style="color:lime;font-size:20px;"></p>

in javascript this becomes variable.style(attribute).color(property)="lime"(value );

You can paste the above code in a notepad and save it as HTML and try it out on your own.



Happy learning.

Suggestions are very much appreciated.

Comments

blog comments powered by Disqus