[SalesForce] Apex Controller Variable value Not Passing to Javascript function

My requirement is:

On the click of a command button, I need to call a controller method and set a value to a controller variable. After that assignment is done, oncomplete attribute of actionfunction should call the javascript code which uses that controller variable value which was set when we clicked on the button. When I did debug the the value using console.log, I don't see any value and it is showing as null. But the Debug statement in the controller is showing the value as expected.

The value is is not passed to VF page JS code. Please let me know if I am doing any wrong in the code. Here's the snippet of the code.

// Javacript Code
<script type="text/javascript">

function secondary ( action) {
   var url;
    if ( action == 'Provider' ) {
        url = "{!MWUrl}";
        console.log('URL ===='+url);       
    }
}

</script>


<apex:actionFunction name="mWProviderSearchURL" action="
{!mWProviderSearchURL}" rerender="form" oncomplete="secondary('Provider');" 
/>
<apex:commandButton onclick="mWProviderSearchURL(); return false;">

public class exampleController {

  public String MWUrl {get; set;}

  public void mWProviderSearchURL() {

    MWUrl = 'https://www.google.com';
    System.debug('MWUrl===='+MWUrl);
  }
}

Best Answer

If you Javascript is outside of your rerender target, then the value won't be refreshed on completion of your server call.

Move the <script> tag inside the form to ensure that it gets rerendered or add it to an outputPanel and add that to the rerender target.