I am trying to send data from client to server nodeJS. But data is not seen on server. What am I missing?
index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var testField = $('#testField').text();
$(document).ready(function() {
$('#submit').on("click",function() {
if ((!$('#testField').val())) {
$('#error').text("Please enter Test");
} else {
$('#error').hide();
console.log ("Ajax call");
console.log ("Inner Ajax call");
$.ajax({
type: 'POST',
url: '/testUrl',
data: testField,
success: function(result) {
console.log ('Response Success:', result);
},
failure: function(result) {
console.log ('Response Failue:', result);
}
});
}
});
});
</script>
</head>
<div id="testId">Test:<input type="text" name="testField" id="testField"> </div>
<div id="error"></div>
<div id="code"></div>
<div id="button"><input type="button" id="submit" value="Submit"></div>
</html>
When I enter value in testField and press enter, it should be received on server.js
Below is the code for server.js
var http = require('http');
var fs = require('fs');
var qs = require('querystring');
function send404Response (response) {
console.log ("send404Response");
response.writeHead(404, {"Context-Type" : "text\plain"});
response.write("Error 404: Page not found");
response.end();
}
function onRequest(request, response) {
console.log ("onRequest");
if (request.method == 'GET' && request.url == '/') {
console.log ("onRequest - GET - Home page");
response.writeHead(200, {"Context-Type" : "text\plain"});
fs.createReadStream ('./index.html').pipe(response);
} else if ((request.type == 'POST' || request.method == 'POST') && (request.url == '/testUrl')) {
console.log ("onRequest - POST - testUrl - " + request.data); //request.data is undefined - how to receive data.
response.end();
} else {
send404Response(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("Server is now running");
request.data is undefined as mentioned in the comment section of above code. I tried visualising the request object via node-inspector. But I don't see the data sent through client to server. Please comment what am I missing.
Thanks in Advance