I'm writing my first plugin and I'm slowly getting there, but I hit on a problem:

I have a controller class in which I have a function that sets a cookie. I call on this function from within a template with actionUrl().

The weird thing is, the cookie is being set (so the controller action is found and executed) but I still get a 404 page on the action path.

Anybody has an idea what could be wrong?

up vote 8 down vote accepted

You're definitely on the right track, just missing out on a couple of key details!

The actionUrl function generates a normal, full URL... it's not (by default) an AJAX call. So your browser is actually navigating away from the previous page, and pinging your controller as a completely separate HTTP request.

Which leads to the next detail... Unless you're pinging your controller via AJAX, you need to then have your controller tell the request where to go. Don't forget, the request will continue on, even after your controller has worked its magic.

... if the controller doesn’t call a response function, Craft will continue on with its request routing...

So you'll usually want to make sure your controller ends with a directive on what to do next. The most common options are:

  • Render a template
  • Redirect to a new page
  • Return a JSON response (if you called it via AJAX)

The list of options to render/redirect/return are mixed in with the other BaseController Methods in the documentation...

  • Ah! I missed that key piece of info too. Thanks. – JamesNZ Sep 26 '16 at 2:07

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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