How to send data from JQuery AJAX request to Node.js server

To get the ‘data’ event to fire on the node.js server side, you have to POST the data. That is, the ‘data’ event only responds to POSTed data. Specifying ‘jsonp’ as the data format forces a GET request, since jsonp is defined in the jquery documentation as:

“jsonp”: Loads in a JSON block using JSONP. Adds an extra “?callback=?” to the end of your URL to specify the callback

Here is how you modify the client to get your data event to fire.

Client:

<html>
<head>
    <script language="javascript" type="text/javascript" src="https://stackoverflow.com/questions/13478464/jquery-1.8.3.min.js"></script>
</head>

<body>
    response here: <p id="lblResponse">fill me in</p>

<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.0.143:8080',
        // dataType: "jsonp",
        data: '{"data": "TEST"}',
        type: 'POST',
        jsonpCallback: 'callback', // this is not relevant to the POST anymore
        success: function (data) {
            var ret = jQuery.parseJSON(data);
            $('#lblResponse').html(ret.msg);
            console.log('Success: ')
        },
        error: function (xhr, status, error) {
            console.log('Error: ' + error.message);
            $('#lblResponse').html('Error connecting to the server.');
        },
    });
});
</script>

</body>
</html>

Some helpful lines to help you debug the server side:

Server:

var http = require('http');
var util = require('util')
http.createServer(function (req, res) {

    console.log('Request received: ');
    util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
    util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });
    res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8080);
console.log('Server running on port 8080');

The purpose of the data event on the node side is to build up the body – it fires multiple times per a single http request, once for each chunk of data that it receives. This is the asynchronous nature of node.js – the server does other work in between receiving chunks of data.

Leave a Comment