Optimal way for sending variable value from php to js script in Moodle

Re: Optimal way for sending variable value from php to js script in Moodle

by Davo Smith -
Number of replies: 0
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

You can get your define function to return an object defining a number of functions and you can call one of those functions from the PHP code to pass in values.

e.g.

define(['jquery'], function($) {
    // Some functions / variables here.
   return {
       init: function(param1, param2) {
           // Do something with param1 and param2.
       }
   };
});
(stored in myplugin/amd/src/myjavascriptfile.js, for example, then run through grunt to generate the amd/build/* files).
Then, in the PHP code:
$PAGE->requires->js_call_amd('myplugin/myjavascriptfile', 'init', ['param1_value', 'param2_value']);

Where 'init' is the name of the function you want to call in the object you returned from the define function and 'param1_value' and 'param2_value' are the values you want to pass in to param1 and param2, respectively.

Average of ratings: Useful (1)