how to get user input and process it in nodejs tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Now we have advanced a bit more and have served an html file from node js in this tutorial.

It would be a matter of updating the html file to have the user input box and adding one more route in node js to wait for specific url, getting the input and posting back the processed data.

In this part, the app will accept a name from the user and will print an email address containing the name that is provided.

How to get input from the user

If you have followed this tutorial, start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input and add the following snippet in it.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     response.sendFile(__dirname+"/views/index.html");
 });
 
 app.get("/getemail", function (request, response){
     var firstname = request.query.firstname;
 
     if (firstname != "") {
         response.send("Your email address is " + firstname + "@gullele.com");
     } else {
         response.send("Please provide us first name");
     }
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


<html>
    <head>
        <title>Simple hello world</title>
        <style>
            .prompt {
                font-size: 16px;
                color: brown;
                font-weight: bold;
                margin-bottom: 5px;
            }
            .container {
                width: 50%;
            }
            .left-pane {
                width: 50%;
                float: left;
            }
            .right-pane {
                width: 50%;
                float: right;
            }
            .submit-name {
                clear: both;
            }
        </style>
    </head>
<body>
    <h1>Hello Node JS</h1>

    <form method='GET' action="/getemail">
        <div class="container">
            <div class="prompt left-pane">
                <span>Give us your firstname and get email address</span>
            </div>
            <div class="right-pane">
                <input type="text" id="firstname" name="firstname" />
            </div>
        </div>
        <div class="submit-name">
            <input type="submit" value="get the email" />
        </div>
        </div>
    </form>
</body>
</html>

7. Save this file and start the sever using

node server.js

8. Now go to browser and surf http://localhost:8080

As you can see, the main point here would be adding one more route app.get("/getemail", function (request, response){ and accessing the parameters using the request object then passing the response with processed name in it.

The next would be to see how node can accomplish rendering the next page with values. And for that, there is a need to have template engine introduced.

Next: Using template engine ejs with node js

how to display html files from node js example tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Here We have see how to print a Hello World for a request of “/”. That is a good advancement but that won’t give us much to proceed. We need a way to server html files for different requests.

So, what we want to do is to have more flexibility by having html file. We will have all the contents as we wish using the old school html tag and we will serve that through node js.

Displaying and rendering html file through node js

If you have followed this then start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     //show this file when the "/" is requested
     response.sendFile(__dirname+"/views/index.html");
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


 <html>
 <head><title>Simple hello world</title></head>
 <body>
 <h1>Hello Node JS</h1>
 </body>
 </html>

7. go to your browser and type http://localhost:8080

You will see Hello Node Js on the browser big and bold.

What is going on

It is like the previous example except we are serving the actual physical html file this time.

By doing so, we have more control on the html file like adding css and javascript codes or calling those files on the page.

Mind you, index.html is the entry point, once we got on that page, we can navigate to other pages and do more

**If the above app is not working for whatever reason, make sure to update npm and get newest version

npm i -g npm-check-updates
npm-check-updates -u
npm insert

Next: Accepting input from the user and processing it.

a hello world tutorial using node js with http web server

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

In order to have simple website that is displaying hello world, we need to have a web server. In the previous example there was no need to have a web server since the message was shown from command line.

Node provides its own web server that we can serve http request and responses.

I will cover on the later tutorial how those would be used, for now. All we need is to be able to go to http://localhost:8080 and see the the output of hello world

Serving the page through web server

If you have followed the above tutorial listed on the link, start from number 3.

1. Create a folder in your computer and name it as node-tutorial

2. In the node-tutorial folder create server.js file

3. On server.js add the following code in it and save it.


 var http = require("http");
 var server = http.createServer(function (request, response) {
 response.writeHead(200, {"Content-Type":"text/plain"});
 response.end("Hello World");
 });
 
 server.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

4. go to your browser and type http://localhost:8080 and you will see Hello World being printed on your browser.

Congratulations! you have successfully created a website that prints Hello World.

What is going on

The above snippet creates a very basic yet full fledged web server. At the heart of any web server are request and response

request is what the browser behalf of the user is sending to the server and it waits for the server to give it back something to show to the user. The request is the one that contains the form elements usually

response is what the server would be responding based on the request forwarded to the server. It contains usually the type of the response data, like text or json or image through its header and the actual data to be returned.

require("http"); This part tells node to import the http package for usage.

With the hello world example above, the request contains no input fields but it is full request in that it is requesting for the response of hello world.

Don’t worry if you don’t get much of the request response stuff, as it would be clear on the upcoming parts of this tutorial.

Since simply printing Hello Worlds is not that much fun. We will see how to do some other exciting stuffs on the upcoming parts of tutorials.

Next: Accept input from the browser/user and process the input

node js mongo db and angular js tutorial for beginners from scratch

node js beginner guide with mongo and angular

node js step by step tutorial showing you how to create a full fledged node js angular js and mongo db for beginners who have never played with these technologies or played partially independently but not all those technologies together.

I assume installing nodejs to your computer can be found easily and I will not go through that.

Starting with a simple Hello world display with webserver

Node js is a fully functional webserver and processor that is created off of Googles V8 engine. It is very light weight and the syntax is javascript syntax.

Unlike other languages where you have to setup and configure a different independent webserver, node js, comes with a total self contained web server serving at ports that you can assign. Which makes it a full one stop web application.

For comparison, when working on php might require you to setup a different webserver like Apache or IIS.

In this part, I will show a very simple old school hello world example to be done in node js.

In the upcoming tutorials, you will see how to change those step by step.

Hello world in node js

1. Create a folder in your computer and name it as node-tutorial

2. in the node-tutorial folder create hello.js file

3 on hello.js add the following code in it.

console.log("Hello World");

Then save the above file and run the file as

node hello.js

This will print Hello World in the CONSOLE.

What did happen

The above code is running from the node js as a command line code. There is no any web server, that making it available through browsers per se, this time, it will just print that on right on the terminal you are running it.

You might know console.log() from your javascript coding and it is doing the same task here in node as well.

Next: Run Hello World using http through browser

Select an element with multiple classes jQuery

CSS Classes, as we know are the main drivers in the UI. Since we have only one id per element, our arena or tweak on that area is almost limited.
But classes are possible to be deployed multiple times per element and we can apply independent actions per classes..
Now, when you have two classes assigned and you want to single out that element having two classes in jQuery you would do

$('.class1.class2')

Without any space in between.
Common usage would be with javascript where you would take and put classes based on actions.

Yup!

Mommy look.. Upgrading jQuery breaks live :(

If you have upgraded jQuery to 1.9 then you would have dreaded Uncaught TypeError: undefined is not a function would be barking at you on your javascript console.

The fix
According to the jQuery site, you would need to replace live with on

Say if you have:

$('.selector-class-name').live('click', function(){console.log('
Applications programming is a race between software engineers, who strive to produce idiot-proof programs, and the universe which strives to produce bigger idiots. So far the Universe is winning.
Rick Cook
')});

Then you would have to change this to the new version using on as follows.
*The current on will be passed the event owner as a parameter so, we have to have a way to know the parent of the event owner, in this case the object with class selector-class-name.
If we don’t know the parent we can implement body tag

$('parent-of-object').on('click', '.selector-class-name', function(){
Applications programming is a race between software engineers, who strive to produce idiot-proof programs, and the universe which strives to produce bigger idiots. So far the Universe is winning.
Rick Cook
});

This shall take care of the problem.

How to dynamically construct Backbone js collection url

Constructing Dynamic URL in backboneJS Tutorial with Example

Working on Backbone js and wanted to pass the url dynamically?

Say you want to fetch the data based on the url


url: someurl/{dynamic-value}/content/{dynamic-value}

Here are some steps to accomplish constructing backboneJS url dynamically based on runtime values.

How to select element with multiple class

Solution

Lets assume your collection looks like this


var Members=Backbone.Collection.extend({
	url: function(){
		return url+'attendees/'+this.options.group;
	},
	initialize: function(models, options){
		this.options=options;
	}
});

On the above example your dynamic url might look like
http://somethingsomething.com/attendees/presenters – where presenters is something you added dynamically

and on your view


var Attendees=Backbone.View.extend({
	el: 'YOUR VIEW',
	render: function(){
		var view=this;
		var member=new Members([], {group: 'presenters'});
		member.fetch({
			success: function(members){
				var template= ...YOUR STUFF GOES HERE
		});
	},
	events: {
		'click #activities': 'membersByActivity'
	},
	membersByActivity: function(){
                YOUR LOGIC..
		return false;
	}
});

The important part for creating dynamic url in backbone js is:


var member=new Members([], {group: 'presenters'});

where you can change the presenters part as you like dynamically