O'Reilly logo

Moodle JavaScript Cookbook by Alastair Hole

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required