Skip to content

Webservice

Emil edited this page Dec 9, 2024 · 16 revisions

Webservice - Connecting Javascript with PHP

The webservices are what specifies what functions the Javascript can call within PHP.

The 4 necessary files

When creating a webservice to allow Javascript to call a function in PHP 4 files are necessary to create/edit.
These files are:

  • db/services.php (edit)
  • classes/external/name_of_class.php (create)
  • amd/src/repository.js (edit)
  • amd/src/JS_file_that_calls_php_function.js (create/edit)

db/services.php

The services.php file is the file that defines what functions that the PHP should allow to be called by the Javascript.
In this file there is a list of functions that is defined, here is an example of a function:

'mod_livequiz_save_question' => [
        'classname'   => 'mod_livequiz\external\save_question',
        'description' => 'Save a question.',
        'type'        => 'write',
        'ajax'        => true,
        'services'    => [MOODLE_OFFICIAL_MOBILE_SERVICE],
    ],

We only need to edit the classname and the description. Here it is important that the classname links to the correct class in the external folder.

classes/external/name_of_class.php

testser

amd/src/repository.js

The repository.js file is where the Javascript defines the PHP functions that can be called.
Here is an example of a function definition:

export const saveQuestion = (question, lecturerid, quizid) => fetchMany([
    {
        methodname: 'mod_livequiz_save_question',
        args: {
            question,
            lecturerid,
            quizid
        },
    }
])[0];

It is important that the methodname is correct, such that it will consist of the module name in this case mod_livequiz_ and the name of the class in this case save_question.
Thus the only thing to edit is the method name and the corresponding arguments.

amd/src/JS_file_that_calls_php_function.js

This is the file that will call the function in PHP, it is important to import the function from repository.js.
Once the function is imported it can be called like any other asynchronous function in Javascript, here an example:

 saveQuestion(savedQuestion, lecturerId, quizId).then((questions) => {
        rerenderSavedQuestionsList(questions, updateEventListeners); // Re-render saved questions list.
        rerenderTakeQuizButton(takeQuizUrl, true); // Re-render take quiz button.
    })
    .catch((error) => window.console.log(error));
Clone this wiki locally