Question

I have a complicated page being rendered by PHP and would like to keep all elements of the page up to date via AJAX long polling. Is there some kind of general / clever way to design an infrastructure to support this without having to specify manually each element to update? Just looking for ideas. Thanks!

Was it helpful?

Solution

Using jQuery, I would send a comma-separated list of jQuery selectors to update to the server. The server will ultimately respond by reading those selectors and producing the HTML to fill up the elements matching the selectors:

$.get("/updater", { elementsToUpdate: "#someDiv,#someTable,#someOtherElement"}, function(json) {
      $.each(json, function(k, v) {

        // the key is the selector, the value is the 
        // HTML to set to that (or those) element(s):
        $(k).html(v);
      });    
}, "json"); // we are expecting the server to return JSON

The server will respond by sending JSON to the client with the following structure:

 {"#someDiv":"this is some HTML to fill up div with ID someDiv","#someOtherElement":"here is some more HTML","#someTable":"here is some more HTML"}

OTHER TIPS

maybe add a special class to all the elements to be updated via ajax, and also you can encode extra data in some other attributes for example

<a class="ajaxUpdate" data="{'a':'json or whatever', 'put whatever here':'ok'}">test</a>

then with jquery you can easily pull out that data and eval it, and use it in your ajax

You can poll a page which returns you the json-encoded structure of your page, like:

var page = {
    'elem1': {
        'html': '<div>... ',
        'update': True
    },
    'elen2': {
        'update': False

and so on, then update what necessary, having only one poll.

Keep your pages elements structure as private data and have the public elements to update them

var page = (function(){
    var private_data = {
    //json
    };

    return {
        workOnData : function(){//process the data}

    }
})()

This is good way you can keep your pages data safe and smooth.

I'd use jQuery to do that if I were you o: then you could do something like...

$('div.updateThisClass').css('color','#fff')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top