I am building a small prototype, and have the following problem:
I am trying to communicate between client-side jQuery, and server-side node.js; when I make a jQuery ajax request to my node.js code, it just gives me the code, not the output of the code.
What am I doing wrong?
Part of client.js:
$.ajax({url : './../includes/get_data.js',
success : function(data) {
alert('success!');
},
error : function(data) {
alert('error!');
}
});
get_data.js:
var fs = require('fs');
console.log('test');
When I make a request to get_data.js, the output I want is: test
But instead I get the source code:
var fs = require('fs');
console.log('test');
Many thanks
You're just asking for a static .js file, you're not interacting with Node at all. If you want to do so, make an HTTP server (copy the example on http://nodejs.org/), bind it to a port and write a response back, don't use console.log (which will only output to the console).
Example:
Save the following file as app.js and then run it in the terminal with node app.js
then visit localhost on port 1337:
var http = require('http'),
ajaxResponse = { 'hello': 'world' },
htmlContent;
htmlContent = "<html><title></title><head>";
htmlContent += "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>";
htmlContent += "<script>$(function() {$.ajax({url:'/ajax',success:function(data){alert('success!');console.log(data);},error:function(data){alert('error!');}});});</script>";
htmlContent += "</head><body><h1>Hey there</h1>";
htmlContent +="</body></html>";
http.createServer(function (req, res) {
if (req.url === '/ajax') {
res.writeHead(200, {'Content-Type': 'text/json'});
res.end(JSON.stringify(ajaxResponse));
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(htmlContent);
}
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
I am guessing you want a GET a certain URL on your server (running Node) that in turn executes the code in get_data.js on your server?
If so, use express - look at http://expressjs.com/api.html#express.