TransWikia.com

Multiple jQuery $.ajax() calls from one template

Craft CMS Asked by Jan Kokes on April 25, 2021

I would like to make multiple Ajax calls from my index.html.

One call comes from $(document).ready() function.
Second one is invoked from .on("click") event outside the $(document).ready() loop.

Unfortunately, the second call seemingly takes success callback from the first call. I tested this by calling a.php in first call and b.php in second call. Both calls end up in a.php, and both have identical parameters.
Is there a way to make this work in Craft?

2 Answers

Craft 3.x controller endpoints are kebab-case rather than camelCase as with Craft 2.x, and you can post to them via JS very easily using the URL format below:

https://yoursite.com/index.php?p=actions/<plugin-handle>/<controller-name>/<controller-action>

To take the example from the old Craft 2 docs you linked to above, you can make an Ajax request to the default endpoint of a controller like this:

https://yoursite.com/index.php?p=actions/cocktail-recipes/ingredients

Or a specific (i.e. non-default) controller action like this:

https://yoursite.com/index.php?p=actions/cocktail-recipes/ingredients/save-ingredient

Answered by Martin Spain on April 25, 2021

The problem seems related to my structure. Yii expects certain controller name, and since I only used a default naming convention in a single controller, Yii keeps calling this controller only.

The problem is that I have no idea how to structure my plugin correctly. https://craftcms.com/docs/2.x/plugins/controllers.html#posting-to-controller-actions-with-javascript doesn't work for me and 3.x documentation doesn't mention it at all.

Answered by Jan Kokes on April 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP