Call php function within Javascript

Call php function within Javascript

by Michele Imperato -
Number of replies: 1

Hello I am new to Moodle plugin development. 

I am using Moodle 3.4 and trying to create a quiz plugin. 

I have a file quiz/classes/quiz_session.php in which there are diffetent functions, one of them (called e.g "function1") update an array containing the students that are attempting for a quiz session retreiving them from a database table. This quiz_session.php file is marked as "defined('MOODLE_INTERNAL') || die();", therefore it's not accessible by browser.

I would call this function1 (contained in quiz_session.php) whithin a javascript setInterval() function in order to update an HTML element  (representing the students attempting the quiz session) each x seconds without updating the whole web page. 

After some research I found that I can call php functions whithin javascript using an Ajax request like this: 

jQuery.ajax({

                    type: 'POST',

                    url: 'classes/quiz_session.php',

                    dataType: 'json',

                    data: {functionname: 'function1', arguments: [1, 2]},

                    success: function (obj, textstatus) {

                    if( !('error' in obj) ) {

                        yourVariable = obj.result;

                    }

                    else {

                        console.log(obj.error);

                    }

                }

});


The problem is that this Ajax request assumes that quiz_session.php is accessible by browser in order to call function1, but it's not since it's an internal file.

Can someone help me please?

Average of ratings: -