title: Poll and get MQTT messages from AJAX in browser
body: <p>Beginner here.</p>
  
  <p>Ok, I'm trying to accomplish a simple data flow:</p>
  
  <p>MQTT-Data-source ---> MQTT Broker ---> NodeJS-MQTT-Client ---> AJAX-on-web-browser (polling-every-3-seconds)</p>
  
  <ul>
  <li>I want to be able to get the MQTT message and show it in the AJAX component in browser side.</li>
  <li>Secondly, on <code>console.log(mqttMessage);</code>, how do i clear previous messages? Because on console I can see all previous data as well as the new data adding up.</li>
  </ul>
  
  <p>I'm using mqtt.js for my nodejs mqtt support on Express.</p>
  
  <pre><code>//Server.js
  var mqtt            = require('mqtt');
  ...
  ...
  
  var getData = function() {
      mqttClient.subscribe(mqttTopic);
  
      mqttClient.on('message', function(topic, message) {
          mqttMessage = message.toString();
          console.log(mqttMessage);
      })
  
      return mqttMessage;
  }
  
  app.get('/pollData', function(req, res) {
      res.send(getData());
  });
  </code></pre>
  
  <p>And on a simple html page, I've got:</p>
  
  <pre><code>&lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"&gt;&lt;/script&gt;
  &lt;script&gt;
      $(document).ready(
          function() {
              setInterval(function() {
                      $.get('/pollData', function(res) {
                          $('#data').text(res);
                  });
              }, 3000);
          }
      );
  &lt;/script&gt;
  </code></pre>