All about programming in GNU/LINUX

Backbone

Sending GET ,POST requests to the server using Backbone.JS and handling them using Node.JS server in the backend

In the last post i discussed about  communicating with the webServer from the browser in the front end using WebSockets .This post too is about sending requests (GET , POST) to the web-server from the browser , but i’ll be employing a different methodology this time around .

So , You might be very curious now about the methodology i’ve employed to interact with the server in this post 😯 😀

In this post  ill be discussing about sending requests to the Node.JS server using Backbone.JS in the front end , Backbone.JS sends AJAX requests to the server.

Backbone.JS is a front end Javascript Library which helps you keep your web application more organized by following MVP(Model View Presenter) approach and it is capable of communicating with the server in RESTful fashion .

First Lets lets see how to send GET request to the server using Backbone.JS and handling it at the backend using NODE.JS webserver which is built using the express framework . Basics of using express framework is also discussed in the last post .

Here is the link for the code from my github.com repo

Here is the Front end code using Backbone.JS to send GET request to the server

<!doctype html>
<html lang="en">
	<head>
		<title>Backbone App</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
		<!--  Underscore.JS is the dependency library for Backbone.JS-->
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
		<!-- Jquery is used for DOM manipulation-->
		<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script>
	</head>
	<body>
		<!--Fieldset helps logically grouping the HTML elements  -->	
		<fieldset>
			<legend>Post Data To Node.JS Server</legend>
			<!-- Input Field to Enter the data to be sent to the server
				Backbone.JS code is written to send POST request to the server 
				on clicking the button -->
			<input type="text" id="course_type" placeholder="Enter the Course Name" required />
			<input type="button" id="post_data" value="Send data to the Server" /> 
	    </fieldset>
	    <fieldset>
	    	<legend>Get Data From Node.JS Server</legend>
	    	<input type="button" id="get_data" value="Get Data From Server">
	    	<!--Backbone.JS code is written to send GET request to the server on clicking the button -->
	    </fieldset>
		<div id="data"></div>
		<!-- Div element where data from the server is placed-->
	</body>
	<!-- Backbone.JS code starts here -->
	<script >
	
		$(document).ready(function(){
			Courses = Backbone.Collection.extend({
					url:'/courses'
				});
	
			$('#post_data').click(function(){
				console.log('Post Clicked');
				post_data_to_the_server();
				
			});
			$('#get_data').click(function(){
				console.log('Get Clicked');
				get_data_from_server();
			});
			
			function get_data_from_server(){
				var courses = new Courses();
				 courses.fetch({
				 	success:function(data_array){
				 		data = data_array.models[0].attributes;
				 		data = JSON.stringify(data);
				 		console.log(data);
				 		var data = "<p>" + data + "</p>" ; 
				 		$('#data').append(data);
				 	}
				 });
		    }  
			
			function post_data_to_the_server(){
				var courses = new Courses();
				courses.fetch({data:{course_name:$('#course_type').val()},type:'POST' });
				$('#course_type').val('');	
			}
		});
		</script>
</html>

request.html

  

 All the functions which start with ‘$’ are derived from JQuery . Plain Javascript can be used instead of JQuery ,its just that coding becomes easier on using Jquery . Backbone Collection is an entity to hold a collection of data .The ‘url’ in the backbone.collection.extend() specifies the URL to which the request to be sent. By using Jquery’s $(‘#button_id’).click() callback functions are associated to the button , which gets executed on click of the button .Backbone.JS sends AJAx requests to the server.
function get_data_from_Server is used to to send GET request to the server Collection.fetch() sends a get request by default and fires the success function when it recieves a reply from the server with data attached in JSON format .Model is an individual entity and collection is a set of different instances of same model.The returned data contains an array of models and its attributes are picked and added onto the html of the page after which the data returned from the server is displayed on screen , Function post_data_to_the_server() is used to POST data to the server.The type:POST argument to the collection.fetch() in the below code makes sure that POST request is sent to the server with the data

Place the html inside a folder called public inside the root of the folder where server.js file is placed. Here is the code for Node.JS server to handle the Bakcbone request

var http = require('http');
var express = require('express');
/* Express Web Development Framework is used */
var app = express();

app.use(express.static('./public'));
/* Specifying the public folder to place the static html and javascripts */

/* app.get listens to GET requests to the URL in the first argument 
   and callback function is executed in respose to it */
app.get('/courses',function(req,res){
	console.log('Get Request obtained from Backbone.JS');
	data = {
		author:"Karthic Rao",
		frontend:"Backbone.JS",
		request:"GET",
		backend:"NODE.JS and Express"
	} /*data to be sent to the client */
	res.writeHead(200,{'Content-Type':'application/json'});
	/* The response type should be a JSON */ 
    res.write(JSON.stringify(data));
    /*The Javascript Object is converted to JSON and sent
     back to the browser as response*/
    res.end();
});
/*app.get listens to GET requests to the URL in the first argument 
   and callback function is executed in respose to it*/
app.post('/courses',function(req,res){
	
	console.log('Post Request Accepted' );
});

http.createServer(app).listen(8124);

Intructions to the run the application

1.Install the server’s dependency module[express in this case]

npm install express 

2.Save the server code as server.js and place the html inside the public folder as course.html

3.Run the application

node server 

4.Go to browser and visit

127.0.0.1:8124/course.html 

Here is the snapshot of the application from browser window

112

I hope that this blog helped you guys understand the basics building a web application with node in the backend and Backbone in the front end , see you guys soon with another exciting post …..Till then Happy Coding 😀

Advertisements

Backbone.js – Listening to DOM events using backbone.views

Writing Backbone.js applications requires three dependies , the Jquery Library , Underscore.js and Backbone.js libraries , this illustrates the simple task of associating a listener for the click event on the checkbox element on the DOM, Backbone.js provides all the necessary functionalities to make a fully fledge web applications , it is well known for the implementation of the MVc architecture , use Ctrl+shift+K in the firefox browser to open the Javascript console and view the console log

<!DOCTYPE HTML > 
<html>
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>

	<script src="http://code.jquery.com/jquery-1.10.2.js">
	</script> 
	
	<script src="http://underscorejs.org/underscore-min.js">

	</script> 
	<script src="http://backbonejs.org/backbone-min.js">
	</script> 
	<script>
		$( document ).ready(function() {
		/*Enclose the script under Jquery Document.ready , this makes sure that the script is executed after the DOM 
		elements on the browser is loaded */
    		var View = Backbone.View.extend({

			el : '#listen_to_box' , 
			/*associate  DOM element on which you want to work on , 
			In this case #listen_to_box is the ID of the div element with the  checkbox */
			
			events: { 
				'click [type="checkbox"]':'clicked', 
				/*associate an event listener 'clicked' for 
				the click event on the checkbox , this is done using the Views events property*/
			},
		clicked : function(event ) { /*The Handler function for the click event on the checkbox*/
			console.log("events handler for "+  this.el.outerHTML);
			/* el.outerHTML has the markup or the HTML code of the DOM element associated with el, 
				in this case the 'div' element with the id of #listen_to_box is assigned to el */ 
		}
	});
	var view = new View();
			
});
					
	</script>
	
	<div id="listen_to_box">
		<input type="checkbox" />
	</div>

</body>
</html>


Js console

Js console