Recently, I had come through a requirement where in I had a form which on submitting runs a sql query to get the data from the database based on the submitted form values.Here the primary requirement was to reload the form after every one minute with the same form data to be passed recursively until the user does not modify it.
So whille the solving this issue, I had come through the following approaches for implementing the Auto Refresh while maintaining the form data:
Approach 1:
The HTML Based META Refresh
I feel that this approach is the best when refreshing a static webpage.
It involves the following syntax
<meta http-equiv=”refresh” content=”60;url=http://localhost:3000/admin?param1=params1¶ms2=param2″>
Here the content = 60 tell the web browser to refresh the page after every 60 seconds the url maps the link to refreshed.
Note: Now when coming to RoR, The url will just represent the action name somewhat like
content=”60;url=/action?param1=params1¶ms2=param2″
The caveat in this method that I found for my requirement was I had form with many fieldsets and form helpers so the string that i passed to url seemed to be looking very ugly.So I decided to go for the ajax based page refresh whcih looks something cooler then this.
Approach 2 :(Recommended)
The Ajax Periodical Updater
I feel this is the coolest way and the one line code to achieve thsi functionality is use the ajax periodical updater. It comes as a Ajax based Rails helper whisch is formatted as follows
<%=periodically_call_remote(:update => “myDiv”,:frequency => 60, :url => { :action => “action_name”, :params=>params }) %>
Here I am updating the div with id as “myDiv” and relading the same at a time interval of 60 secs.I had to place this div at the immediate start of the HTML body tag and before the immediate end of the body tag as my requirement was a full page reload.
The periodically_call_remote is rendered in the HTML Template as follows
<script type=”text/javascript”>
//<![CDATA[
new PeriodicalExecuter(function() {new Ajax.Updater(’myDiv’, ‘/action_name?params1=params1& params2=params2, {asynchronous:true,evalScripts:true})}, 20)
//]]>
</script>
So wrapping up, I would like to say that the moral of this post I would like to ajax can be used to refresh the page, there by breaking the bounds of the so called REST architecture.
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.