2

I have a web service where I fetched my data and populate it in my client. As of now, I have a button that will fetch data from the web service when clicked using ajax get. On my web service, I have a maintenance where I will be able to add, edit or delete data. What I want to do is to have my client automatically fetched data from my web service everytime I add, edit, or delete data, so it will show accurate data to the client.

Here's what I'm thinking. On my web service, i will have a json that will tell true/false whether the data has been updated (will be fetched by the client). So every add, edit, delete will turn that to true, and every time the client fetched that data, it will become false.

Now, I need to have a javascript/jquery listener that will listen to any change in that json (the true or false). I need to have that listener run every second? Is it possible?

Thanks.

EDITED:

I've been rereading my post, and it hits me, I'm just thinking with only one client in my mind. Every add,edit,delete in my web service will turn the "updated" to true, and everytime I get a request for the data, I'll set it to false. But how about the other clients? When they sent a request, it's already false, so they will not update it. Any ideas? Thanks

2
  • The only thing you can do is to poll the server in intervals Commented Jul 22, 2012 at 3:13
  • I recommend looking into Socket.IO for a good web sockets wrapper. Commented Jul 22, 2012 at 3:14

2 Answers 2

4

You can do this using two aproaches:

  1. Web sockets; or
  2. setInterval function.

Here is an example of setInterval().

// just a control var...
var gen = 1;

// call the function repeatedly in 5 seconds of interval
// this call returns an id that can be used to stop the calls
var id = setInterval(function(){

    // function body...

    alert( "making an ajax request...(" + gen + ")" ); // here you call your webservice
    gen++;

    // just want to stop it, but you wont need this.
    if ( gen == 10 ) {
        clearInterval( id );
    }

}, 5000 ); // 5000 miliseconds == 5 seconds

Some links:

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

1 Comment

Will it exhaust more resources (CPU or bandwidth, or anything which is concerned) when we are using setInterval indefinitely like this? Or is it the same as using websockets?
0

You've got two HTTP options: polling the server, or using a comet request. If you're polling, it might work better to include the last updated time in the request so the server can filter any events older than that time. That way, you don't need to save an extra flag for every event for every client.

Comments

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.