I am a newbie with ajax and I have to display a template only when clicking on a button. This template is weighing and it will be on all pages, so I want to use ajax.

Someone can help me?

2 Answers 2


Primarily, this is a Javascript question, not a Craft CMS question. For the Javascript part of this, I would look for general AJAX tutorials or try searching on Stack Overflow.

But rather than downvote this question as being off-topic, here are some things to help on the Craft CMS side of things.

You can create a template to generate a chuck of HTML you want to include in other pages.

For example, if you create a file called:


You can access that from http://mysite.com/includes/example no matter if it's directly in a browser or thru an Ajax request from another page.

If you need to test wether a template is being accessed directly thru a browser or an Ajax request, you can test that with craft.app.request.isAjax:

{% if craft.app.request.isAjax %}
{% else %}
{% endif %}

If you'd rather have your Javascript deal with JSON data instead of a chuck of HTML code, you have a few options.

You can name a file with the .json extension and file-based routing will automatically serve that URL as the content type 'application/json'.


Or you can use the Element API plugin. This is a much more performant solution, but require some PHP knowledge.


Quick and dirty (with jQuery, sorry!)

<div id="templatePlaceholder"></div>

   var fragmentUrl = '{{ url('path/to/template') }}';

But read Alex's answer for proper context :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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