jquery ajax success event handler not getting called

  • Node.js (express) web server
  • Request handler in web server
app.get('/documents/ajax/:id.:format?', function(req, res) {
   console.log ('Request Received');
   var body = 'hello world';
   res.writeHead(200, {
    'Content-Length': body.length,
    'Content-Type': 'text/plain'
   });

})
  • ajax request from client side javascript
  $.ajax({
    url : "/documents/ajax/" + item,
    success : function(msg) {
      alert ("success" + msg);
    },
    error : function(request, status, error) {
      alert("Error, returned: " + request);
      alert("Error, returned: " + status);
      alert("Error, returned: " + error);

    }
  });
  • I am able to receive the request on server side and I send 4 requests

But my success event is not getting called in client side JS. Also, when I stop my web server, then I see my error handlers get called.

Please help.

The main issue is that you are not ending the response so the server never actually sends anything to the client. The server should respond with something like a file, a redirect, some text, etc. You need to finish the callback with a res.end, res.send, res.sendfile, res.redirect, res.render... See the docs.

Furthermore, with express you want to use res.set to set the http headers:

app.get('/documents/ajax/:id.:format?', function(req, res) {
   console.log ('Request Received');
   var body = 'hello world';
   res.set({'Content-Type': 'text/plain'});
   res.send(body);
});

200 is the default response code, so you don't need to specify that and the length will be computed for you. These things are often easier to debug from the command line via curl:

curl http://localhost:3000/documents/ajax/1

and

curl -I http://localhost:3000/documents/ajax/1

I had to res.end in server request handler. After that I was able to generate success event in client side JS