General developer forum

Moodle Course ID

 
Picture of Leander H
Moodle Course ID
 

Hi guys,

i'm new to moodle and i would like to write an moodle mod. So i need to load some data and send it back to the client. On the client side there is js Code so i do this with an ajax request. For this loading i need the course Id. The Problem is that i don't get the right id. The code snipped:

<?php
require_once('../../config.php');

if(isset($_POST['action'])){
$action = $_POST['action'];

switch ($action){
case 'loadSomething': loadSomething($_POST['uid']); break;
}
}
function loadSomething($uid){
global $COURSE;
$courseId = $COURSE->id;//wrong

/...load../

echo json_encode($result);
}
>
The $COURSE Variable contains the information about moodle and not about the course the mod is located.

Can someone help me?

 
Average of ratings: -
Picture of Sam Chaffee
Re: Moodle Course ID
Core developersParticularly helpful Moodlers
Hi,


If you take a look at lib/setup.php and search for $COURSE you will see that it defaults to a clone of the $SITE variable, which is why you are seeing the site info, rather than some other course. $COURSE is updated with some other course info when require_login() is called from your script passing a course ID. To do that you would need to pass a course ID with your AJAX call or retrieve it from a session variable or something like that.

That all said, there a couple of things you might want to consider. The first is to use Moodle's built-in web services for your AJAX (see https://docs.moodle.org/dev/AJAX and https://docs.moodle.org/dev/Web_services). The second is that if you choose not to use Moodle's web services for AJAX (which may be reasonable sometimes) you should most likely use require_login() and likely have a capability check using has_capability() or require_capability() and instead of directly accessing $_POST you should use Moodle's required_param() or optional_param() functions to get those values cleaned.

Cheers,

Sam

 
Average of ratings: -
Picture of Leander H
Re: Moodle Course ID
 

Hi,

thanks for the help.

So I have one more question: Is there a possibility to get the course ID on the client side? So that i could pass it with the Ajax Call.

Cheers,

Leander

 
Average of ratings: -
Picture of Sam Chaffee
Re: Moodle Course ID
Core developersParticularly helpful Moodlers

Hi,

You'd have to pass it from the server side when you include your JavaScript on the page so it depends on how you're including your JavaScript into the page.

Cheers,

Sam

 
Average of ratings: -