kema

Messenger

Nov 19th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     $('#submit').click(send);
  3.     $('#refresh').click(refresh);
  4.  
  5.     let hostUrl = "https://ajaxdemos-bfee6.firebaseio.com/messenger.json";
  6.  
  7.     function send() {
  8.             let message = {
  9.                 author: $("#author").val(),
  10.                 content: $("#content").val(),
  11.                 timestamp: Date.now()
  12.             };
  13.         if(message.author!='' && message.content!=''){
  14.             $.ajax({
  15.                 method: 'POST',
  16.                 data: JSON.stringify(message),
  17.                 url: hostUrl,
  18.                 success: function () {
  19.                     $("#content").val('');
  20.                     refresh()
  21.                 }
  22.             });
  23.             // $.post(hostUrl, JSON.stringify(message)).then(function(){
  24.             //     $("#content ").val('');
  25.             //     refresh();
  26.             // });
  27.  
  28.         }
  29.  
  30.     }
  31.  
  32.     function refresh() {
  33.         $.get(hostUrl)
  34.             .then(function (result) {
  35.                 $('#messages').empty();
  36.                 let keys = Object.keys(result).sort((m1, m2)=> result[m1].timestamp - result[m2].timestamp);
  37.                 for (let msg of keys) {
  38.                     $('#messages').append(`${result[msg].author} : ${result[msg].content}\n`)
  39.                 }
  40.             })
  41.     }
  42. }
Add Comment
Please, Sign In to add comment