silkAdmin
silkAdmin

Reputation: 4810

Node.js retrieving data from node into jquery ajax callback

I have a jquery ajax call that send a request to the node.js app that works fine, the problem is that i can not retrieve any response with the jquery call back.

The Jquery

$(document).ready(function(){
    var listing = $('#listing');

    $.ajax
    ({
        url: "http://my.ip.is.here:3000/",
        cache: false,
        //timeout: 5000,
        success: function(data)
        {
            listing.append(data);
        }
    });

})

Node:

var s = http.createServer(function (req, res) {
    req.on('data', function(sock) {

      // SEND DATA BACK TO AJAX HERE

    });

});

s.listen(3000, 'my.ip.is.here');

console.log('Server running at http://my.ip.is.here:3000/');

How should i do to retreive data from the node.js app into my jquery callback? ( and hopefully while keeping the connection alive )

Upvotes: 3

Views: 2602

Answers (1)

Javo
Javo

Reputation: 627

If you want to trigger the data event on the server, you have to send data to the server, maybe using Jquery's post method as in:

var postSomething = function(){

    $.post
    (
        "http://127.0.0.1:3000/",
        {wooo:'wooo'},
        function(data)
        {
         console.log(data);
        }
    );
}

Also, when the server triggers the 'data' event, you should write some data in the response object:

req.on('data', function(sock) {
      res.writeHead(200, {"Content-Type": "text/plain"});
      res.end("Hello!!");
});

However, if you just want to retrieve data from the server, I don't think you need the data event on the server, and can just handle the request as in:

var s = http.createServer(function (req, res) {
          res.writeHead(200, {"Content-Type": "text/plain"});
          res.end("Hello!!");
});

If you use 'end' you will be ending the request, if you want to keep it active, you can just use 'write'. This way, the connection is still active, and you stream data to the client each time you write data into the response object.

Hope this helps!

Upvotes: 3

Related Questions