title: Long polling with Node.js and ajax
body: <p>I have following <strong>server code</strong>.</p>
  
  <pre><code>var http = require('http');
  var mysql = require('mysql');
  var querystring = require('request');
  var util = require('util');
  var url = require('url');
  
  var singer_name;
  var currentmodif, lastmodif;
  var requests=[];
  var response;
  
  var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'someone',
    password : 'xxxxxxx',
    database : 'rest',  //mysql database to work with (optional)
  });
  connection.connect(); //connect to mysql
  
  connection.query('SELECT * FROM musics WHERE id=1', function(err, rows, fields) {
    if (err) throw err;
  
    singer_name=rows[0].singer_name;
    currentmodif=rows[0].time_added;
  });
  
  
  http.createServer(function (req, res) {
      console.log('request received');
  
      requests.push({
          response: res,
          timestamp: new Date().getTime()
      });
  
      if(req.method=='GET'){
          var url_parts = url.parse(req.url,true);
          lastmodif = url_parts.query.timestamp;
      }
  
      //check_update(req, res);
  
  }).listen(9000);
  
  
  setInterval(function() {
  
      var expiration = new Date().getTime() - 30000;
  
      for (var i = requests.length - 1; i &gt;= 0; i--) {
          //console.log("Request timestamp: "+requests[i].timestamp+" Expiration : "+expiration);
          response = requests[i].response;
          if (requests[i].timestamp &lt; expiration) {
              console.log("The condition is met");
              response.writeHead(200, {
              'Content-Type'   : 'text/plain',
              'Access-Control-Allow-Origin' : '*'
              });
  
              // return response
              response.write('_testcb(\'ok\')', 'utf8');
              response.end();
              //break;
          }
      }
  
      connection.query('SELECT * FROM musics WHERE id=1', function(err, rows, fields) {
          if (err) throw err;
          currentmodif=rows[0].time_added;        
              //console.log("currentmodif: "+currentmodif+" lastmodif: "+lastmodif);
          if (currentmodif &gt; lastmodif){
              singer_name=rows[0].singer_name; 
              var _arrays = {'singer_name': singer_name, 'time': currentmodif}
              var data = "_testcb"+"("+JSON.stringify(_arrays)+")";
              response.writeHead(200, {
              'Content-Type'   : 'text/plain',
              'Access-Control-Allow-Origin' : '*'
              });
              if (response.end(data))
              console.log("Response successfully sent");
              //return false;
          }
  
      });
  }, 2000);
  </code></pre>
  
  <p><strong>and Client code:</strong></p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
      &lt;script src="http://code.jquery.com/jquery-1.10.1.min.js"&gt;&lt;/script&gt;
      &lt;title&gt;Node.js Ajax test&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;/body&gt;
  &lt;script&gt;
  var timestamp = "1380020402";
  function callNode() {
  
  var time = "1380020402";
      $.ajax({
          url: 'http://xx.xxx.xx.xxx:9000/',
          dataType: "jsonp",
          data: {"timestamp":timestamp},
          type: 'POST',
          jsonpCallback: "_testcb",
          cache: false,
          timeout: 35000,
          success: function(response, code, xhr) {
              if ('ok' == response) {
                  callNode();
                  return false;
              }
  
              console.log(response);
  
              timestamp = response.time;
              // make new call
              callNode();
          },
          error: function(jqXHR, textStatus, errorThrown) {
              console.log('error ' + textStatus + " " + errorThrown);
          }
      });
  }
  $(function () {
      callNode();
  });
  &lt;/script&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I am trying to do a long polling. So until a data in database is updated, the response to ajax request should be paused but the above code is not working. I am making the ajax request from different domain and therefore using jsonp. </p>
  
  <p>Exact problem is that currently when the data is changed in database the response doesn't get sent. It works every now and then but it is not consistently reliable.</p>
  
  <p>Another problem is that the code block for time out is not working. If the request is 30 seconds old then a blank response should be sent in order to avoid the timeout from ajax.</p>
  
  <p>If someone can help then I would appreciate.</p>
  
  <p>Cheers.</p>