javascript - How to get and append most recent messages from server using jQuery and AJAX? -
i'm working on first simple chat application , issue has me stuck. know i'm trying do, end overthinking it.
basically, have heroku server going:
http://tiy-fee-rest.herokuapp.com/collections/blabbertalk
whenever sends message, added array.
my issue:
i have on set interval every 2 seconds, runs getnewestmessages function. when setinterval working , sends message, keep appending last message sent every 2 seconds. if disable setinterval , call getnewestmessages function myself in separate browser tab, doesn't seem happen. i want make sent message isn't re-appended dom when setinterval active.
this function i'm using check recent messages. it's pretty bloated, sorry that:
getnewestmessages: function() { $.ajax({ url: http://tiy-fee-rest.herokuapp.com/collections/blabbertalk, method: 'get', success: function (data) { // finds id of recent message displayed in dom var recentid = $('.message').last().data('id'); var prevmostrecent = 0; var newmostrecent = []; jquery.each(data, function(idx,el){ if (el._id === recentid) { // if 1 of messages on server has id equal // 1 of messages in dom, saves index in var prevmostrecent = idx; } }); jquery.each(data, function(idx,el){ if (idx < prevmostrecent) { // if there messages on server lower index // recent message in dom, pushes them new // array. basically, creates new array of messages newer // last 1 displayed in dom. newmostrecent.push(el); } }); (var = 0; < newmostrecent.length; i++) { console.log(newmostrecent[i]); if (newmostrecent[i]._id === $('.message').last().data('id')) { // attempt @ trying remove last dom message // array of newer messages. main issue // whole function keep appending recent message // on , on again. var result = _.without(newmostrecent, newmostrecent[i]); console.log('message excluded: ', newmostrecent[i]); // if array of newer messages contained recent // dom message, removes , sends appended. page.appendnewestmessages(result); } } // if array of newer messages doesn't contain recent // dom message, sends whole array normally. page.appendnewestmessages(newmostrecent); }, error: function (err) { } }); }
here append function:
appendnewestmessages: function(messagestoappend) { console.log(messagestoappend.reverse()); _.each(messagestoappend.reverse(), function(el, idx, arr) { var newmessage = { content: el.content, timestamp: el.timestamp, author: el.author, usericon: el.usericon } $.ajax({ url: page.url, method: 'post', data: newmessage, success: function (data) { page.addonemessagetodom(data); }, error: function (err) { console.log("error ", err); } }); }) }
can me understand how recent messages server , append them dom without repeats? has been driving me nuts.
thanks , help.
Comments
Post a Comment