Using ajax to check for changes on server

Using ajax to check for changes on server

I'm trying to use ajax to check every 5 seconds if content on my server has changed since the user loaded it. I understand I must use advanced HTTP caching to make sure my server isn't hammered down to the ground because of this.

My server is set up to return the `Last-Modified` HTTP header, including `302 Not Modified` if that is the case.

On the client-side I've set `ifModified: true`, as well as `If-Modified-Since` in `beforeSend` to the value of `Last-Modified`. But I'm having trouble understanding how all this fits together. Other than setting `If-Modified-Since`, where am I supposed to actually use it? And, how do I check for change inside `success`?

globalVar.firstRequest = true; globalVar.lastModifiedDate; $.articlePoller = { poll: function() { console.log('Ran poll'); setTimeout(this.request, 5000); }, request: function() { console.log('Ran request'); var dataUrl = $('#articles').data('url'); $.ajax({ url: dataUrl, type:"GET", cache: true, ifModified: true, Async: true, beforeSend: function(xhr){ if(!globalVar.firstRequest) { // HELP!!! xhr.setRequestHeader("If-Modified-Since", globalVar.lastModifiedDate); } }, success: function(html, textStatus, xhr){ if(globalVar.firstRequest) { console.log('First request'); globalVar.firstRequest = false; globalVar.lastModifiedDate = xhr.getResponseHeader('Last-Modified'); // Start again $.articlePoller.poll(); } else { console.log('Subsequent request'); // HELP!!! if(???) { console.log('We have change! Proceeding to fetch the actual content...'); $.articlePoller.addArticles(); } } } }); }, addArticles: function(articles) { // ... }, showArticles: function(e) { // ... } }; $(function() { $.articlePoller.poll(); $('#show_articles a').click($.articlePoller.showArticles); });