1

I wan to call a js function when the index.html loads.

This js function is defined in main.js file.

I am able to call it using the below way

           <input type="button" value="Submit" onclick="getSecretData()" />

But i want this function to be called every time the index.html is loaded (instead of the button)

I tried the below code. Its not working. Can you please help ?

                index.html 

    <script>
        $(document).ready(function() {

        getSecretData();


        });
        </script>


    main.js 

        function getSecretData(){
    var invocationData = {
        adapter: "DummyAdapter",
        procedure: "getSecretData",
        parameters: []
    };

    WL.Client.invokeProcedure(invocationData, {
        onSuccess: getSecretData_Callback,
        onFailure: getSecretData_Callback
    });
    }

    function getSecretData_Callback(response){
    alert("getSecretData_Callback response :: " + JSON.stringify(response));
    }

Thanks

Idan Adar
  • 44,156
  • 13
  • 50
  • 89

2 Answers2

0

You are using Worklight. Did you read the training materials?

Other answers given here could work for you, but because you are using Worklight, you should do it in the more appropriate approach for Worklight-based applications.

In your Worklight application, in common\js\main.js, there is wlCommonInit().
If you want some code to run when you start your app, place it there.

function wlCommonInit() {
    myFunction();
}

function myFunction(){
    // whatever you want to run...
}

Note though, that it is not smart to invoke adapters on application startup. Adapters require connection to the Worklight Server, so what you want to do is to first try and connect to the server using WL.Client.connect and if you succeed in doing so, only then invoke the adapter via the connect's onSuccess callback.

WL.Client.connect({onSuccess: myFunction, onFailure: connectionFailure});

For example:

function wlCommonInit() {
    WL.Client.connect({
        onSuccess: myFunction,
        onFailure: connectionFailure
    });        
}

function myFunction(){
    // whatever you want to run...
}

function connectionFailure(){
    // ...
}
Idan Adar
  • 44,156
  • 13
  • 50
  • 89
0

You can try this.

document.querySelector('body').addEventListener("load", getSecretData, false);

For more information I recommend reading this previous answer or MDN's page

Community
  • 1
  • 1
Gary Storey
  • 1,779
  • 2
  • 14
  • 19