Search code examples
loopsasynchronouscoldfusionrefreshcfquery

Coldfusion - Refreshing Page When A Database Record Updates


Good day,

Let me describe my problem :

Scenario :

  • User 1 has a coldfusion webpage, containing 6 alerts as html elements populated using a database. User 1 is constantly monitoring this page for changes.
  • A user on a different computer (different session) logs into a admin console and add's a 7th element and inserts it into the database.
  • The database contains a field that changes from 0 to 1 as soon as an alert is added and inserted into the database.
  • The webpage of User 1 not has to dynamically refresh or update with the 8th alert.

Problem :

  • I am struggling to run a async loop that queries the database permanently for the record that tells it there is a change, while not freezing the rest of the page.

Solution :

  • I need to run a cfquery to check the isUpdated field in the database.
  • That cfquery needs to be run every minute.
  • As soon as the cfquery returns a 1, the page should refresh which in turn will populate the new alert as well.

Solution

  • Can be done through sockets, and you do not have to check the availability of a new record every minute.

    You can also do it with javascript/jquery:

    <script>
    var lastAlert = '#lastAlert#'; //last at the time of loading the page
    
    setInterval(function() {
        lastAlert = isUpdated(lastAlert);
    }, 60000);
    
    function isUpdated(lastAlert){
    res = lastAlert;
    $.ajax({                            
        url: 'checkAlerts.cfm', //in this file do check for changes in the database. should return the number of the last alert
        type: 'POST',
        data: {lastAlert:lastAlert},
        cache: false,
        success:function(res){  
            if(res > lastAlert){
                //your code if there is a new entry 
                alert('a new entry has been added');
            }
        }
    });
    return res;
    }   
    </script>
    

    I did not check the code! But I hope you understand how to proceed.