I am new with jQuery and I'm having a hard time getting my page to continually update as results come in from my java servlet. I want like a timer effect on the web page as new time values are coming in from the servlet.
On my webpage I have something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script>$(document).ready(function(){$.get("/timer", function(data){$('H1').append(data); })})(); </script>
And in my servlet timer I have a while loop that uses the response.getWriter() to write the new time value for like 30 iterations:
//this is in my doGet function
while(count <30 ){
count++;
out.println(count);
}
The problem is when I load the page nothing gets appended to the page until the 30 iterations are done. Is there a way to get each it iteration print out to show on the page?
Thanks
out.flush() will write whatever is in the buffer to the browser.
Remember though that if you have a long running server operation, you may need a better mechanism so that the server knows when client goes away/stops the operation so that server can stop the processing too. Also, you can have a better user experience by not needing to navigate to another page, by leveraging javascript
Typically, a javascript timer/poll is used to obtain status of the operation (on the server, you may have the operation running on a separate thread - this also serves as a keep-alive message to the server - if the server does not receive a alive, it may want to stop the processing for efficiency )
Long polling and html5 web socket (you will need support on the server for web socket) are other approaches -
see: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery