PHP to Javascript passing value

Struggling to Pass Values from PHP to Javascript in Moodle? Here’s a solution

Lots of Moodle developers have been struggling to pass dynamic values to the JS page. Some developers tend to write inline JavaScript code in the PHP page itself, which is a bad practice and Moodle discourages the same.

Some create hidden elements in the DOM and access the values in the JS files. But this approach would create an unnecessary element in the DOM.

Now let’s explore the correct and the easiest way to pass values to JS files.

Follow the below steps to pass variable values to JS files.

Step 1. First include the JavaScript file on your PHP page.

Step 2. Then initialize that file with the following values as follows;

where the first argument to js_init_call is the initialization function name that will be written on the JavaScript page and will be called automatically when the page loads.

Below is the code for init function to be written in the js page

Note that the first parameter Y, which is an instance of the YUI object, is automatically passed to our function by the Page Requirements Manager.

The second parameter is the variable in which we are actually receiving the initialization data

Are You Looking for Moodle Development Solutions?

You can see that we have assigned the initvariables value to initvalues global variable and now we can use this global variable throughout the js page.

Try printing the initvalues values in console out of the scope of init function

This will print all the values in the form of a JavaScript object.


Contributed By:

Surendra Prasad

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge