0

I am facing a situation where actionFunction is getting called from javascript when the actionFunction is placed above the script tag. However if their positions are reversed the actionFunction does not fire.

<apex:page controller="JqDAtaTAble">

<apex:includescript value="//code.jquery.com/jquery-1.11.1.min.js" />
<apex:includescript value="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js" />
<apex:stylesheet value="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css" />
<apex:form >
  <table id="dattable" class="display">
      <thead>><tr><th>first</th></tr></thead>
      <tbody><tr><td>hello</td></tr><tr><td>hello</td></tr></tbody>
  </table>
  <apex:actionFunction name="onloadAct" action="{!generateData}" oncomplete="jsmethod()"/>
  </apex:form>

  <script>  

    onloadAct();

    function jsmethod(){
    alert('hello alert');
    $('#dattable').DataTable({

    });
    }
   </script>

Why doesn't the onloadAct method not fire in the below case:

<apex:page controller="JqDAtaTAble">

<apex:includescript value="//code.jquery.com/jquery-1.11.1.min.js" />
<apex:includescript value="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js" />
<apex:stylesheet value="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css" />

  <script>  

    onloadAct();

    function jsmethod(){
    alert('hello alert');
    $('#dattable').DataTable({

    });
    }
   </script>
<apex:form >
  <table id="dattable" class="display">
      <thead>><tr><th>first</th></tr></thead>
      <tbody><tr><td>hello</td></tr><tr><td>hello</td></tr></tbody>
  </table>
  <apex:actionFunction name="onloadAct" action="{!generateData}" oncomplete="jsmethod()"/>
  </apex:form>

1 Answer 1

2

Scripts are parsed by the browser top to bottom. Therefore, in the second case, you attempted to call the method before it was defined. If you want to have the script defined before the action function, you can, but you need to delay calling the method until it is available:

<script>  
window.addEventListener("load", function() {
        onloadAct();
});
function jsmethod(){
alert('hello alert');
$('#dattable').DataTable({

});
}
</script>

By waiting until the page is loaded, you'll be able to call the function, because it will then be defined in the browser's JavaScript engine.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.