Hello friends,
This time i am going to create very simple AJAX based visual force page for the beginners.
What is AJAX?
As many of you already know that the AJAX stands for the “Asynchronous javascript and XML“.
AJAX is the art of exchanging data between server and client without reloading the complete web page.
Visualforce and AJAX
Visualforce has inbuilt support for the AJAX. using the attribute “rerender” we can specify that where the response should be rendered.
Example:
Lets have an example to demonstrate that how simple AJAX works in visualforce.
Create an APEX class with following code.
public class AjaxDemo { private String currTime; public String getCurrTime() { return currTime; } public void setCurrTime() { currTime = System.now().format('EEEE, MMMM d, yyyy - hh:mm:ss'); } }
As you can see in above Apex class, i have created method named “setCurrTime()” which will set the value of string variable. There is also one get method named as “getCurrTime()” which returns the value of that variable.
On the basis of above Apex class lets create Visualforce page with below code.
<apex:page Controller="AjaxDemo"> <apex:pageBlock Title="Ajax Sample"> Hello <b> {!$User.FirstName}</b>. <apex:form > <br /><br /> <apex:commandbutton action="{!setCurrTime}" rerender="ajaxresult" value="Display Current Time" /> </apex:form> </apex:pageBlock> <apex:pageBlock title="AjaxData"> <apex:outputPanel id="ajaxresult" layout="block"> Result: {!CurrTime} </apex:outputPanel> </apex:pageBlock> </apex:page>
There are few points to observe from above visualforce page
- Apex class earlier created is referenced using attribute “Controller” of “apex:page” tag.
- On “apex:commandbutton” we have specified that after clicking on button which method of the class should be called using attribute “action“.
- After the action completion of commandbutton which part of the apex page should gets refreshed is specified by attribute “rerender“.
- in outputpanel i have specified that which method should gets executed to get the result by simply giving the method name. In this case its {!CurrTime}
Output would look like:
Leave a Reply