Call PHP function from JS in extension

I’ve got an extension that doesn’t have a controller and has a single PHP file that pulls in some javascript files. I need to send some data from a JS function back to a PHP function.

Looking at Yii Playground and any other examples that I could find, there is always a controller and the data is sent using an AjaxLink. Is there another way to do this without a controller? If not, how do I add the controller to the extension?

You cannot add a controller to the extension, you should create a standard controller in controller and call a widget or a function on some class that you define in the extension.

zaccaria, I actually added another controller to add actions, but my extension displays on multiple other controller pages. It really doesn’t seem like the correct thing to do to keep all the extension files together.

After researching this some more, a widget or module may be the way to go but I’m not sure which would be easier. The widget doesn’t allow you to add a controller, so it won’t work unless there is another way to get the data from JS back into the database.

Right now I can call the javascript functions that I need from the PHP and I have my data sitting in JS and ready to be sent back to the server to update in the database. I could do this by adding an action to the SiteController that gets specified in the ajax, but that is a little hackish. Turning the extension into a module would allow me to add a controller and give a place to put the action.

Would this end up being too heavy of a solution for something this simple? How else can I get the data from JS back to PHP and in the database?

I usually add a controller or an action to a controller.

Try to keep it simple:

the basic developing is creating controllers and views (in your case, view is not needed).

Just write a new controller or, if you already have a controller in which make sense to place this action, add the action to the controller.

As everithing is working fine, you can do something more stylish in order to reuse this work in future project.

You can include this work in an extension or create a module for it.

A module can host many controller, so if you just need an action, add it to a controller and that’s absolutely ok.

Anyway I advice you to make all work, and in a second time think if you can do something of more stilish.

Not sure if it was mentioned, but why not create a separate action class? That’s what action classes are meant for. Similar to CCaptchaAction a user of your extension can configure that action in any controller he prefers.

See here for details on how to write such a class:

http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#action