Friday 27 November 2015

How to make java script function will execute after the controller method executed?

As we all know java script function will execute first then controller method executes, In some case we need java script method should execute first. Below is the work around for this case.

Instead of normal java script we will use on load java script which means when page loads/refresh that java script function will execute. Again it will be problem because each and every time that method will execute. How to avoid this ?

We will use a Boolean variable to control execution.

public Boolean isJavascriptInvoked {
        get {
            if (null == this.isJavascriptInvoked ) {
                this.isJavascriptInvoked = false;
           
            }
            return this.isJavascriptInvoked ;
        }
        set;
    }

public PageReference test(){

    // your method logic
    isJavascriptInvoked = true;
   return null;

}

<script>
   If({!isJavaScriptInvoked} == 'true'){
       // javascript logic.
  }
 
</Script>

When page loads isJavascriptInvoked will be null or false since it is boolean type,So javascript method wont execute since there is a condtion defined. When controller method invoked by some action then isJavascriptInvoked value will be set as true then js method will execute.

1 comment:

Jeet said...

Hi Ashish,

One way i am thinking is to invoke JS methods calling from "oncomplete" attribute instead of making any get; set; method. After the action will perform executing apex codes, the oncomplete attribute will invoke the JS methods. I feel that there will no need of having separate variable. Happy coding.. :)