Reputation: 13
i can't figure out why i can't retrieve the form input values in node.js sent by a jquery ajax call:
here is the client side jQuery code:
$('#send-button').click(function(event) {
event.preventDefault();
var str = $('#form-contact').serialize();
$.ajax({
type: 'POST',
url: "contact",
data: str,
success: function(msg) {
....
},
error: function(XMLHttpRequest, textStatus) {
....
}
})
now in node.js i try to retrieve the data send by the jQuery ajax request:
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
qs = require('querystring'),
fs = require("fs"),
var server = http.createServer(function(request, response) {
.....
path.exists(filename, function(exists) {
if(!exists) {
if (paramUri == "/contact") {
if (request.method == 'POST') {
var body = '';
request.on('data', function(chunk) {
body += chunk;
});
request.on('end', function() {
console.log(body);
})
}
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('worked');
return;
}
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
......
});
})
server.listen(8080);
but the request.on('data') and request.on('end') are never called. i am using node.js -v 0.2.6
Upvotes: 0
Views: 1285
Reputation: 21241
You are using path.exists()
which is a async function. This becomes a problem when you register your request listeners not until you're acutally executing this callback.
The solution is to pause the request before you execute path.exists()
and resume it in the callback:
...
request.pause();
path.exists(filename, function(exists) {
//register request listeners
...
request.resume();
}
Upvotes: 1