Database polling using jQuery / Ajax

I'm trying to use jQuery (latest version) and ajax to poll the mysql db every x seconds, post.php does a simple lookup on the table and it limits to 1 row. (e.g. SELECT id FROM TABLE LIMIT 1)

I have some other jQuery UI code (using v1.8) that displays some modal / dialog boxes on the screen, just put if post.php returns something from db I need to initialize the dialog to pop up to the screen. I've done all the popups, I'm just having problems with all these bits - I've added some pseudo-code of how I expect this to work. thanks in advance

var refreshId = setInterval(function(){
    $.ajax({
       type: "POST",
       url: "post.php",
       data:  "",
       success: function(html){
         $("#responsecontainer").html(html);
       }
   });  
}, 2000 );s

/* proposed pseudocode */
if (ajax is successful & returns a db row to #responsecontainer) {
   show jQueryUI modal (done this bit already fortunately)
}

      

+2


a source to share


1 answer


Why don't you just handle everything in the success block? As you seem to have polled some data, I would also suggest using JSON .

var refreshId = setInterval(function(){
    $.getJSON('post.php', function(data){
        if (data.message.length > 0) {
            $("#responsecontainer").html(data.message);
            /* your jquery ui stuff here */
        }
    });  
}, 2000);

      



See jQuery for the getJSON documentation for details .

Note. POST should be used to send data, GET to receive data. If you want to know why and what additional details you can take a look at REST .

+3


a source







All Articles