All about programming in GNU/LINUX

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

13 responses

  1. Reblogged this on Sutoprise Avenue, A SutoCom Source.

    February 1, 2014 at 12:25 pm

  2. Reblogged this on Sutoprise Avenue, A SutoCom Source.

    February 6, 2014 at 1:01 pm

  3. Pingback: Backbone, Links And Resources (4) | Angel "Java" Lopez on Blog

  4. Pingback: Algorithms using python:Graph Algorithms-1:Depth First search | hackintoshrao

  5. Pingback: Algorithms using python:Graph Algorithms-1:Depth First search | hackintoshrao

  6. Arseny

    Why the post request in the last photo is pending ?

    June 17, 2014 at 9:18 pm

    • The POST request to the server was sent but was still waiting for the reply form server !

      June 18, 2014 at 1:41 am

  7. Pingback: Intro to AngularJS and Client Server communication using nodeJS and AngularJS:Posting data to the Node-Express server using AngularJS | hackintoshrao

  8. Ashwin

    Was struggling to understand how to send POST requests using fetch. This article really helped me a lot!

    July 28, 2014 at 11:06 am

  9. help me, I was copied this code into your project, but I have a problem , console show a “resource interpreted as document but transferred with mime type application/json”/ and all my json i see as plain text in body

    August 15, 2014 at 8:23 pm

  10. This looks like issue with recent version of the library . Currently i dont work on Backbone.JS for MVC purposes , i use AngularJS now . Im unable to recollect from my memory why exactly this issue occured , please consider posting it in stackoverflow.com

    August 18, 2014 at 12:04 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s