Passing variables from PHP to JavaScript
In the previous recipe, we learned how to run our JavaScript function, but we did not pass any data to it. In this recipe, we will pass two parameters to the JavaScript function — a message to be displayed and the current user's username, demonstrating how to make variable values from PHP available within our JavaScript code.
Getting ready
Create a new PHP file requirejs_init_data.php
with the following content:
<?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/requirejs_init_data.php'); $PAGE->requires->js('/cook/requirejs_init_data.js'); $PAGE->requires->js_init_call('hello', array('Hello', $USER->username)); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?>
This code sets up a simple Moodle page and includes a JavaScript file requirejs_init_data.js
containing the following basic "Hello World" function that we will call, which accepts three parameters.
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 two subsequent parameters are strings to be passed to the function: message
and username:
function hello(Y,message,username) { alert(message + ', ' + username); }
Now when we load the page, we see that our JavaScript alert is executed, displaying the message we passed along with the current user's username (admin):
How to do it...
Just after the call to $PAGE->requires->js
, add the following code:
$PAGE->requires->js_init_call('hello', array('Hello', $USER->username));
The first parameter is a string containing the name of the JavaScript function we wish to call, which is hello
in this case.
The second parameter is a PHP array of values that are passed on to the JavaScript function in the order in which they are defined.
The use of an array here allows the js_init_call
method to support an arbitrary number of arguments, two in this case: the message and username
.
How it works...
We have used the Page Requirement Manager to register the name of the function we wish to be called and passed two additional parameters required by the function inside a PHP array.
When the document is rendered, the following JavaScript will be generated inside a <script>
tag just before the end of the <body>
tag:
hello(Y, "Hello", "admin");