In this chapter, we will cover:
Creating a new Moodle PHP page
Loading a JavaScript file
Loading a JavaScript file in
<head>
Generating a JavaScript function call from PHP
Passing variables from PHP to JavaScript
Ensuring compliance with XHTML Strict
Retrieving language strings from Moodle
Web pages and websites have come a long way since their inception in the early 1990s (with the creation of HTML). Modern web applications such as Moodle now have far more in common with desktop applications than with the simple word processing documents they originally modeled.
One key weapon in the modern web application's armory is the subject of this book — JavaScript.
In essence, JavaScript is a programming language that runs in a user's web browser rather than on the web server. It allows programmers to manipulate the web page via what is called the Document Object Model (DOM). The DOM is a representation of the underlying HTML page, structured in a way to provide access to each and every element within the HTML page. Modern browsers now implement a standard version of the DOM, so it can be considered a cross-platform technology.
In recent years, there has been a significant uptake of the use of JavaScript frameworks. A JavaScript framework is a library of JavaScript code that makes a JavaScript programmer's life easier. Generally, they provide more efficient methods for performing the most common tasks in JavaScript, such as locating DOM elements or wiring up events to those elements. (An event is a function of an element. For example, an HTML input button element has a "click" event that is fired when the mouse is clicked while the pointer is over the button.) Additionally, they provide an abstraction of browser-specific quirks, making it very easy to write cross-platform code that works in the widest range of browsers.
One such JavaScript framework is the Yahoo! User Interface library (YUI). YUI is the framework of choice for Moodle 2.0, and is included with the standard Moodle 2.0 package. For this reason, a substantial number of techniques covered in the later chapters will be based on the YUI. In the final chapter, we will briefly explore some other popular JavaScript frameworks and libraries.
Perhaps more important than "how" to use JavaScript is the question of "when" to use it. It is vital to consider the target audience of your web applications and infer from this exactly how you will use JavaScript.
If you are building a web application that is to be widely used in a public setting, then you should aim to make it as accessible as possible to all types of users. With respect to JavaScript specifically, this means that the core functionality of your site should be available to those who, for whatever reason, cannot or will not use a browser that fully supports JavaScript (typical examples include a mobile device which has limited functionality, or a browser using automated text-to-speech or screen-reading software). These techniques form a part of what is known as "progressive enhancement".
In this first chapter, we will learn the basic techniques for integrating our JavaScript code with Moodle 2.0. We will learn several methods of including our JavaScript code in a Moodle page via .js
files, and how to get the code to run. Lastly, we will look at some best practices and also how to make Moodle data and language strings available to our JavaScript code.
The code examples used in the recipes throughout this book are all based on the template we will create in this recipe. This template sets up the necessary Moodle environment and displays the standard Moodle header and footer.
This will allow us to look at the generic tools and techniques available to us within Moodle that pertain to JavaScript, allowing you, as the developer, to decide how and where to apply them.
In most instances, it is highly recommended to work with Moodle's rich plugin infrastructure to extend any functionality. This allows you to keep your enhancements completely separate from the core of Moodle, preventing you from introducing bugs into the core code, and making the Moodle upgrade process just a case of ensuring that your particular plugin folders are copied into the upgraded Moodle installation.
Please refer to the Moodle documentation at http://docs.moodle.org/ to decide which plugin framework suits your requirements.
There may be rare cases when it is simply not possible to implement the functionality you desire inside the plugin frameworks, requiring the modification of core code. If this is the case, it is likely that the functionality you desire will be useful to all Moodle users. Therefore, you should look to engage with the Moodle development community to seek advice regarding the feasibility of having your changes included in the next revision of the core code.
If, however, you know for a fact that you definitely need to make changes to core code and that those changes will only be useful to your bespoke use of Moodle, you may consider (as a last resort) modifying the core code files. Be aware that this method is not without issues, incurring significant disadvantages, such as:
Keeping track of each change you make to each file, and merging these changes as you upgrade to future versions of Moodle. Version control systems such as CVS or GIT may assist you here.
Your changes will not be subject to the same standard of testing and debugging as that of the official core code.
Your changes will not be guaranteed to continue to work in future versions; you will need to fully test your changes with each future upgrade.
So, as you can see, there is a trade-off in functionality versus maintainability for each method of extending and enhancing Moodle; so you should choose wisely. If in doubt, use a plugin or theme!
To begin with, we will create a subfolder named cook
within our Moodle installation where we will put all the files we will work with throughout the book.
Next we will create the template PHP file blank.php
, with the following content:
<?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/blank.php'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?>
Note
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
We now have our template saved at /path/to/moodle/cook/blank.php
.
To test this new template, we can load it in a web browser and check if all is well. Assuming we have a web server running with Moodle served at the base URL http://localhost/moodle
, we can load the following URL to test our new template: http://localhost/moodle/cook/blank.php
.
If the template is set up correctly, we will see a basic page with standard header and footer, similar to the following:

We begin by opening the PHP tags in the standard way, using <?php
.
Note that we have not used the shorthand notation of <?
, as this goes against the Moodle programming guidelines and also against general good practice.
Next, we must include Moodle's global configuration file. The inclusion of this file sets up the requisite Moodle programming environment, including two global variables we will make use of: $PAGE
and $OUTPUT
.
$PAGE
is defined as a central store of information about the current page we are generating in response to the user's request.
The $PAGE
object allows us to start defining the properties of the page, namely the context and the URL. The context of the page is the scope of the page, that is, where in the Moodle system it is being used. We are using the System context; other examples are in the Course or Module context.
Next, we set the URL of the page. This mirrors our directory structure; so in this case we just set it to /cook/blank.php
.
$OUTPUT
is defined as an instance of core_renderer
or one of its subclasses. Use it to generate HTML for output.
The $OUTPUT
object allows us to generate the header
and footer
for our page, based on the current Moodle theme. This is done by calling the header and footer methods of the $OUTPUT
object, and using echo to write them to the page.
After opening the PHP tag, we can begin inserting the PHP code. We use require_once
to include the Moodle configuration file (this ensures that the file is included only once, and will halt execution of the page if the file is unavailable). The path to the configuration file is determined by using the dirname
function to get the directory path to the current file (using the built-in __FILE__
constant), and then traversing up one directory (as we are in our cook
subdirectory) to find the config.php
file.
Next, we set the page context by calling the set_context
method of the $PAGE
object. This takes a context instance. We retrieve the instance for the system context by passing the CONTEXT_SYSTEM
constant to the get_context_instance
function.
The final usage of the $PAGE
object is to set the page URL, which is done using the set_url
method, passing in a web root relative URL path, which is /cook/blank.php
in this case.
Next, we need to use the $OUTPUT
object to generate the header and footer of the page. Both header and footer methods return HTML as a string, so we can use the echo
construct to write these strings to the page.
A majority of the JavaScript we add will be contained within an external JavaScript file, which is a text file with a .js
extension. In this recipe, we will learn how to use the $PAGE
object to include such a file.
Make a new PHP file named requirejs.php
in the cook
directory similar to the template in the previous recipe:
<?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/requirejs.php'); $PAGE->requires->js('/cook/alert.js'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?>
Next, we create the accompanying JavaScript file, alert.js
, with the following content:
alert('Hello World!');
Now when we load the page in a web browser, we see that the JavaScript alert is displayed as shown in the following screenshot, proving to us that our code has loaded and executed correctly:

Note that we see the Home button, meaning that the footer of the page has loaded. This is because our code is executed at the end of the <body>
tag.
We have created a page based on the blank template we created in the first recipe of this chapter. To this, we have added the following line:
$PAGE->requires->js('/cook/alert.js');
We are making use of the Page Requirements Manager, $PAGE
, which is an object that contains various methods for setting up additional components for a page. Here we have called the $PAGE->requires->js
method, and passed the path to our .js
file as a parameter.
Moodle then adds this script to the list of scripts to be included within the final rendered page. A <script>
tag similar to the following will be inserted just before the closing <body>
tag:
<script type="text/javascript" src="http://localhost/moodle/lib/javascript.php? file=%2Fcook%2Falert.js&rev=1"></script>
Note
The <script>
tag is inserted at the end of the <body>
tag, inline with the current best practice, offering the best page performance and a simplification of handling DOM-ready events among other reasons. For a fuller discussion of this technique, please refer to the Yahoo! Developer Network resource at the following URL:
http://developer.yahoo.com/performance/rules.html#js_bottom
This code must be included after the Moodle configuration file config.php
has been included. This is where the $PAGE
object is setup for us.
In the previous recipe we learned the standard method of including a JavaScript file at the end of the document's <body>
tag.
In this recipe, we will look at how to ensure our JavaScript file is included within the <head>
tag. There are numerous reasons why you would require your file be included within the <head>
, for example if you need to use document.write
to manually write <head>
content.
Note
If you are in any doubt, use the technique in the previous recipe. If you need to use the technique in this recipe, the chances are you will know exactly why.
Once again, open the Moodle PHP file where we will add our .js
file. We will use the simple example from the previous recipe as a basis, with the necessary changes:
<?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->requires->js('/cook/alert.js', true); $PAGE->set_url('/cook/requirejs_head.php'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?>
Now when we load the page, we see that our JavaScript alert is executed immediately, assuring us that our code is loading and executing correctly, as seen in the following screenshot:

Note that the page underneath is blank at this stage, as our JavaScript code is being run from the <head>
tag, before the rest of the page has loaded.
You will notice that this code is almost identical to that of the previous recipe. The key difference here is the parameters we have passed to the $PAGE->requires->js
method. We have passed a second optional parameter which determines whether or not the <script>
tag will be rendered within the document's <head>
tag. In this case, we set it to true
to ensure that the <script>
tag is rendered as such.
We have called $PAGE->requires->js
again, this time with two parameters. The first is the path to the .js
file we wish to include. The second is a Boolean value which specifies whether or not to include the file from within the <head>
tag of the HTML page.
The <script>
tag that is rendered to the document is identical to that of the previous recipe, with the crucial difference that it is rendered within the <head>
tag, rather than at the end of the <body>
tag.
Now that we have loaded our JavaScript file, we need a method to execute that code. Once again, we may use the Page Requirements Manager $PAGE
to generate a call to our JavaScript function.
Note
This recipe describes a basic technique for executing your JavaScript code when the page is loaded. More sophisticated techniques based on handling DOM events with the Yahoo! User Interface library will be covered in later chapters.
Set up a page requirejs_init.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.php'); $PAGE->requires->js('/cook/requirejs_init.js'); $PAGE->requires->js_init_call('hello'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?>
Set up the accompanying JavaScript file, requirejs_init.js
, with the following content:
function hello(Y) { alert('Hello World!'); }
Now when we load the page, we see that our JavaScript alert is executed, assuring us that our code is loading and executing correctly, as seen in the following screenshot:

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.
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):

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
.
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");
Moodle uses the DocType XHTML Strict. We should take care to ensure our JavaScript maintains compliance with this standard.
Although it is best avoided, it may occasionally be necessary to include JavaScript code within <script>
tags that are embedded within the page. If this is the case, it is highly likely that the code will include characters that have special meaning to the XHTML Strict specification, for example &
and <', '>
to name a few.
Open the PHP file that contains the embedded JavaScript and locate the start and end <script>
tags.
Add the following code immediately after the opening <script>
tag:
<script language="JavaScript" type="text/javascript"> //<![CDATA[
Add the following code immediately before the closing <script>
tag:
//]]> </script>
The CDATA
tag we have used informs the XHTML rendering engine that it should treat anything inside as arbitrary data, and not to attempt to parse it as if it were valid XHTML markup.
Additionally, to avoid a conflict with JavaScript syntax, the lines on which the CDATA
tags reside have been commented out with double forward slashes (//).
Moodle makes extensive use of language strings to support full multilingual internationalization. In practice, this means that strings which are used within the interface are held in language-specific files. For example, the string "Submit assignment" may be held in the relevant English language file, and this string may be referred to indirectly via a short name key.
This makes it trivial to support additional languages by creating files for those languages. As the code refers to the strings via their short name keys, it is easy to simply switch the set of language files, and the code will pick up the strings in the new preferred language. This happens automatically when a user changes their preferred language settings.
When providing textual feedback to the user from our JavaScript code, we should make use of Moodle's language string system. This ensures our code is inherently multilingual and makes it easy for a non-developer to provide a language translation of our module.
In this example, we will retrieve the built-in Moodle language string course
and show that it is available from our JavaScript code by displaying it with the alert function.
We start once again with a basic Moodle page and associated .js
file:
<?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/requirejs_init_lang.php'); $PAGE->requires->js('/cook/requirejs_init_lang.js'); $PAGE->requires->string_for_js('course', 'moodle'); $PAGE->requires->js_init_call('lang'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?>
As you can see, this code registers a call to the function lang
which has been defined in the associated .js
file:
function lang(Y) { alert(M.str.moodle.course); }
Now when we load the page, we see that our JavaScript alert is executed, displaying the language string value we set up, as seen in the following screenshot:

We have included our .js
with the method now familiar — $PAGE->requires->js.
After this line comes a new feature of the Page Requirements Manager, the string_for_js
function:
$PAGE->requires->string_for_js('course', 'moodle');
Finally, we refer to this language string from our JavaScript code:
alert(M.str.moodle.course);
We call the string_for_js
method with two parameters: the name of the string we wish to retrieve and the location of this string. In this example, we are retrieving the language string for course
from the core Moodle language file.
Now this string is made available to us as part of Moodle's global JavaScript namespace (M) in the format, M.str.<module name>.<string name>
. In our example, this is M.str.moodle.course
.
Using this method, the strings we have set up will be available to all subsequent JavaScript code. If we had simply passed this string as a parameter to the JavaScript function, it would only be available inside that function. If we required it to be available within additional functions, we would have to repeat the process, making copies of the string and passing those to the additional functions resulting in unnecessarily inefficient code.