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:
<?phpThe $COURSE Variable contains the information about moodle and not about the course the mod is located.
$action = $_POST['action'];
case 'loadSomething': loadSomething($_POST['uid']); break;
$courseId = $COURSE->id;//wrong
Can someone help me?
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.
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.