I often get asked how to get Node.js working with JQuery and AJAX. Of course you can always use something like Socket.IO for realtime, but sometimes you might be dealing with older browsers that don’t support WebSockets and AJAX might be a safer way to go. Incidentally, if you do want to use Socket.IO check out my article on how to get started. Today I’ll show you a very quick and simple way to get JQuery, Node.js, CoffeeScript and AJAX all talking together.
Note: If CoffeeScript is not your language of choice, then you can easily convert the code to JavaScript using this handy online tool (it can convert both ways: CoffeeScript to JavaScript and JavaScript to CoffeeScript).
Assuming you already have Node.js and NPM installed and working create a new folder for this project. If your on OS X open up the Terminal and navigate to the new folder you just created and install the following Node.js packages:
$ npm install express $ npm install -g coffee-script
Lets create a file called server.coffee and add the following code to it:
express = require("express")
app = express.createServer(express.bodyParser())
app.listen 8080, "127.0.0.1"
app.get "/", (req, res) ->
res.sendfile __dirname + "/index.html"
app.post "/echo", (req, res) ->
returnJsonObj =
echoMessage: req.body.message
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(returnJsonObj));
console.log " Server Listening on 127.0.0.1:8080"
Update Sept 14, 2012: With Express 3 keep in mind that createServer has been deprecated. You can modify the above code like below to get rid of the deprecation warning:
app = express(); app.use(express.bodyParser())
Above I created a very simple web server that will hand out an index.html webpage as well as answer an incoming request wich we will use JQuery to talk to it.
Create a file in the project folder called index.html and add the following code to it:
<!DOCTYPE html>
<html>
<head>
<title>JQuery AJAX with Nodejs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<script>
$(function() {
$("#callAjax").click(function() {
var theMessage = $.trim($("#theMessage").val());
if(theMessage.length > 0)
{
$.ajax({
type: "POST",
url: "http://localhost:8080/echo/",
contentType: "application/json",
data: JSON.stringify({
message: theMessage
}),
dataType: "text",
success: function( data ){
var returnedJsonObj = JSON.parse(data);
$("#echoResult").html("You said: " + returnedJsonObj.echoMessage);
},
error: function( err ){
$("#echoResult").html("Error: " + err);
}
});
}
});
});
</script>
<strong>Echo Message:</strong>
<input type="text" id="theMessage" name="theMessage" value="" />
<input id="callAjax" type="button" value="Call Ajax" />
<div id="echoResult"></div>
</body>
</html>
Note: The above JavaScript for the index.html file is written in JavaScript, you can actually write that in CoffeeScript as well. See this article for more information on that.
Run the server.coffee file by doing this:
$ coffee server.coffee
Go to this link once the server is running: http://localhost:8080/
Expected Results:
Keep in mind this is only one way of doing this, there are several other ways to do this as well as a lot more features that can be added.




