0

I need to display currently stored data on website which refreshes itself automatically only if the data changed.

My current approach which failed:

  • request data from database let's say every 10s
  • check if this data differs from the currently displayed one

What I did:

setInterval(function() {refreshData()}, 5000);

function refreshData() {
        @{
            var db2 = Database.Open("StarterSite");    
            string tresc2 = db.QuerySingle(someQuery, 3).Tresc;


            <text>
                alert(@tresc2);
            </text>


        }        
    }

the problem here is that this code seems to be working fine, I do not get any error messages but @tresc2 does not exist. It looks like db2 also does not exist.

I do not understand what is going on here.

Two questions if I may:

  • what should be a proper approach to my problem?
  • what do I do wrong here?

Thank you

1
  • 1
    alert needs quotes around the argument. Commented May 1, 2014 at 20:37

1 Answer 1

1

The code at the server side gets executed and when it renders, it becomes

setInterval(function() {refreshData()}, 5000);

function refreshData() {
    alert(somevalue);
}

What you get then is that you constantly call the very same function that alerts the very same message.

A more correct approach would be to ajax-call the server and update the page:

<div id="divToRefresh" />
<script type="text/ecmascript">

   $(function() {
     setInterval(function() {refreshData()}, 5000);

     function refreshData() {
       $.ajax( {
         url : 'controller/action',
         async : false,
         success: function(data) {
           $("#divToRefresh").html(data);
        }
     }
  });
</script>

This assumes that the controller/action controller/action returns a partial html that contains a refreshed fragment of your page.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. Do not know much about AJAX and I need to have my problem solved ASAP so if possible: could you please tell me where in the ajax function you mentioned should I add my request to the database (I should probably mention that my web page is not MVC).
@JacekWojcik: the call to the database is done at the server side. The url of the ajax call can point to anythhing, mvc, webforms, whatever.
To force browser to display new data it is also necessary to set cache = false as a parameter for $.ajax method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.