<!DOCTYPE html>
<head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</script>

<body>
  <h1>TempMessenger</h1>
  <div></div>

  <form action="/messages" id="postMessage">
    <input type="text" name="message" placeholder="Post message">
    <input type="submit" value="Post">
  </form>

  <script>

  function poll() {
    $.ajax({
      type: "GET",
      url: "/messages",
      dataType: "json",
      success: function(data) {
        console.log('poll complete', data);
        updateMessages(data);
      },
      timeout: 500,
      complete: setTimeout(poll, 1000),
    })
  }

  poll();

  function updateMessages(messages) {
    var content = "<div>";
    if (messages.length == 0) {
      content += "<p>No messages!</p>";
    } else {
      $.each(messages, function(index, value) {
        content += "<p>" + value.message + "</p>"
      });
    };
    content += "</div>";
    $("div").replaceWith(content);
  }


  $( "#postMessage" ).submit(function( event ) {
    event.preventDefault();

    var $form = $( this ),
      message = $form.find( "input[name='message']" ).val(),
      url = $form.attr( "action" );

    $.ajax({
      type: "POST",
      url: url,
      data: JSON.stringify({message: message}),
      contentType: "application/json",
      dataType: "json",
      success: this.reset()
    });

  });
  </script>
</body>
