How do I make a live update to a section of a page?

I need to refresh sections of my page to refresh when new data appears! What am I doing? use jquery?

examples:

+2


a source to share


5 answers


Yes, jQuery is great for this. Explore these methods:



http://api.jquery.com/category/ajax/

+2


a source


jQuery is usually not required for basic AJAX. A simple example would be the following:



liveSection = document.getElementById('latest-news');
request = new XMLHttpRequest;
request.open('GET', '/news-ajax', true);
request.send(null);
request.addEventListener('readystatechange', function() {
  if (request.readyState == 4 && request.status == 200)
    liveSection.innerHTML = request.responseText;
}, false);

      

+1


a source


If you are using Asp.NET why not use UpdatePanel ? It's simple and reliable.

Edit

I'm just re-reading your question and it looks like (based on how you phrased it) that you want to update the user's webpage when the data is changed on the server. I just want to make sure you understand that in a web application, the server cannot force the browser to do anything. The server can only respond to browser requests, so you need to check the server against the server periodically.

0


a source


I created a simple example (using jQuery) to help you figure out what should happen:

1 - Polling the server periodically (via ajax) using Javascript setTimeout

to check that the latest content is loaded in the browser. We can achieve this by extracting the last element id or whatever and comparing it to the variable that was initialized on the first page load.

2 - If the element id does not match (a little oversimplified) we can assume that there was an update, so we replace the content of some element with some content from some page.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    function getLatestStuff() {

        // fetch the output from a context which gives us the latest id
        $.get("isthereanupdate.aspx", function(response) {

            // we have the response, now compare to the stored value
            if(resp != lastItemId) {

                // it different, so update the variable and grab the latest content
                lastItemId = response;
                $("#latestStuffDiv").load("updates.aspx");
            }
        });
    }

    $(document).ready(function() {

        // the value which initializes this comes from the server
        var lastItemId = 7; 
        setTimeout(getLatestStuff, 10000);
    });
</script>

      

0


a source


If you want to update when new data is available, you should look at comet or pubsubhubbub. jQuery can help you display the data nicely, but you will need to write stuff on the server to send the data.

0


a source







All Articles