2

Until now I've always done backend plugin development but my next task is to create a homepage with craft. To make an Ajax request I used Craft.postActionRequest but if I try this in my frontend template I always receive the error Uncaught ReferenceError: Craft is not defined

I've tried to include {%- includejsresource "js/craft.js" first -%} but it does not work. Of course I could just create a normal request via Ajax/jQuery but I would like to do it with craft methods...

So my question: what do I have to do, to get access to craft.js library? edit: Just like this https://craftcms.com/docs/plugins/controllers#posting-to-controller-actions-with-javaScript

Thank you very much

3

The global Craft object available in the Control Panel is exposed in the craft.js file, which is a bundle containing most of the JavaScript code used in Craft's Control Panel (i.e. admin area).

This file is not meant to be used in your front end!

The craft.js file has dependencies on other CP-only JavaScript files, and weighs – by itself – a whopping ~250 kb minified, which is a lot of bytes to force on your end users just because you'd like to use a tiny part of the library in your front end code. Additionally, because the file is only meant to be used with core functionality in the Control Panel, it can be updated/changed by Pixel & Tonic at any time (i.e. any time Craft is updated), possibly breaking your custom code which depends on it.

Instead of using the whole craft.js package, I'd strongly advice you to cherry pick (i.e. copy and paste) any methods or functionality you need from craft.js to a custom JavaScript bundle. For specific functionality (e.g. AJAX requests), you might also consider using other, established open source libraries (like SuperAgent, Axios or even jQuery).

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.