<p>You can create a custom plugin with <a href="https://pluginfactory.io/" rel="nofollow noreferrer">Pluginfactory.io</a> and check the box for <code>Controllers</code> but leave the name blank. Copy the downloaded files into your <code>path/to/craft/craft/plugins/&gt;&gt;nameofyourplugin&lt;&lt;/</code> directory and install it in your cp. </p>

<p>Then you'll insert a function like this in your controller</p>

<pre><code>public function actionRenderTemplate(){
    $id = craft()-&gt;request-&gt;getParam('id');
    // do some checks if the id is valid or not here...

    $html = '';
    $success = false;
    $message = '';

    if($entry = craft()-&gt;entries-&gt;getEntryById($id)){
        // as example to render different templates based on entry type
        $entryType = $entry-&gt;getType()-&gt;handle; 
        $html = craft()-&gt;templates-&gt;render('path/to/your/template/' . $entryType, array(
            'entry' =&gt; $entry
        ));
        if($html){
            $success = true;
        }
    }else{
        $message = Craft::t('could not find entry with id ' . $id);
    }

    $this-&gt;returnJson([
        'message'   =&gt; $message,
        'success'   =&gt; $success,
        'html'      =&gt; $html
    ]);
}
</code></pre>

<p>And your Javascript could be this </p>

<pre><code>$('.load-instrument').click(function(){
    var data = {
        action: "pluginname/actionRenderTemplate",
        id: $(this).data('id')
    };
    $.ajax({
        type: "post",
        url: '',
        data: data,
        success: function(data){
            if(data.success === true){
                $("#idOfYourDiv").html(data.html);
            }else{
                // display error messages here
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            console.log("Status: " + textStatus);
        }
    });
});
</code></pre>

<p>However I would recommend you to read the <a href="https://craftcms.com/docs/plugins/introduction" rel="nofollow noreferrer">docs</a> about <a href="https://craftcms.com/docs/plugins/controllers" rel="nofollow noreferrer">Controllers</a> and about <a href="https://craftcms.com/docs/plugins/templates" rel="nofollow noreferrer">templates</a> to fully understand what you have to do here</p>

<p>edit: your html could be </p>

<pre><code>&lt;button data-id="{{instrument.id}}" class="load-instrument" value="click me"&gt;Click me&lt;/button&gt;
</code></pre>

CC BY-SA 3.0
2018-01-27T12:00:39.703Z
Thanks Robin! Wow! Let's see if I get this sorted.
analog junkie
CC BY-SA 3.0
2018-01-27T12:02:12.317Z
Just tell me if you have any questions. If it's totally new to you and you can't solve something we can go to the chat as well.
Robin Schambach
CC BY-SA 3.0
2018-01-28T17:15:00.500Z
Yes, it is definitely above my level of skills. How do I implement the plugin into the site and how does it load the include?
analog junkie
CC BY-SA 3.0
2018-01-28T20:37:44.673Z
Unfortunately you can't use the chat yet (you need 20 reputation points) so we have to stay here until you got them. I provided a few links, the question how to implement the plugin is explained in the first one. Create a new folder in your `craft/plugins` directory and set the name of the folder how you named the plugin in pluginfactory.io (all lower case) and copy the downloaded files. In your cp you have settings -> plugins you'll need to install the plugin there. As for the include, you won't have an include anymore since you'll load your template in your controller and not in twig anymore
Robin Schambach
CC BY-SA 3.0
2018-01-29T07:51:31.103Z
Making and installing the plugin was fine. Now I need to fiddle how to get the template to work. How do i call the id in the plugin, like I did it in the "onclick"-script (document.getElementById('{{teacher}}') to get the right data from craft I am calling in the for loop. 
I am very fresh to building websites, so I am leaning out of the window a lot (as one would say in german ;-)) and I am very grateful for your help.
analog junkie
CC BY-SA 3.0
2018-01-29T07:53:23.143Z
https://craftcms.com/docs/plugins/controllers#posting-to-controller-actions thats your `data` variable in javascript `var data = {
        action: "pluginname/actionRenderTemplate",
        id: $(this).data('id')
    };` the `action` attribute defines the routing path, so you'll insert `yourPluginHandle/actionRenderTemplate` In case you are not able to make it work, please tell me your handle and the name of your controller class. I suggest you to read the links I posted
Robin Schambach
CC BY-SA 3.0
2018-01-29T08:32:19.610Z
I created a "test" once for another user with a full working example of a javascript request here https://github.com/Anubarak/usernotifications you can see a template https://github.com/Anubarak/usernotifications/blob/master/templates/entries/entrytypes/shortMessage.twig a Controller https://github.com/Anubarak/usernotifications/blob/master/controllers/UsernotificationsController.php#L36 and the javascript to communicate https://github.com/Anubarak/usernotifications/blob/master/resources/js/java.js#L2
Robin Schambach
CC BY-SA 3.0
2018-01-29T13:59:22.753Z
I think the controller class is "TonartLayersController" and the plugin Name is "tonartlayers".
analog junkie
CC BY-SA 3.0
2018-01-29T14:01:45.137Z
So your action parameter will be `tonartLayers/renderTemplate` and the ID - of course - the Id of the teacher or instrument you want to display. Do you have any issues?
Robin Schambach
CC BY-SA 3.0
2018-01-29T14:35:21.427Z
Sorry, I can't bring it to work and I don't really understand much of what I am doing here. So it is hard for me to look for the missing bits and pieces. I guess I will leave it for now and come back to it when I have more time and know more about php and javascript.
analog junkie
CC BY-SA 3.0
2018-01-29T14:38:53.143Z
Well you need to communicate what is working and what parts are causing trouble. We can't provide any help if you just say "it does not work" otherwise you won't solve your problem.
Robin Schambach
CC BY-SA 3.0
2018-01-29T14:41:45.560Z
Well the link doesn't react when clicked. Does it need to be a "button" in order to call the plugin?
analog junkie
CC BY-SA 3.0
2018-01-29T14:43:42.320Z
Do you attach the jquery event properly? Did you even include the Javascript part I posted? Is there something in your network tab in your browser console or in your browser console at all? Any errors? It does not matter if it is a link or a button, hell even a div works
Robin Schambach
CC BY-SA 3.0
2018-01-29T15:22:02.720Z
I included the javascript directly into the html with a <script> tag. I am not sure, which bit was the jquery? I also tried the html you provided.
analog junkie
CC BY-SA 3.0
2018-01-29T15:22:41.893Z
The browser-dev-tool shows the markup but no reaction.
analog junkie
CC BY-SA 3.0
2018-01-29T15:25:10.500Z
Not the cleanest way but it should work. Did you include jquery in your head? https://www.w3schools.com/jquery/jquery_get_started.asp. It's not about what your browser displays, it's about your console. Please press F12 and open the "console" tab, then refresh the page you'll see runtime errors there. Make sure your link has the correct class so you bind the click event. If this little task is far to much for your maybe you should think about if creating a website is a little bit too much at this moment. You should start with small tasks if you have absolutely no clue what's going on
Robin Schambach
CC BY-SA 3.0
2018-01-29T15:44:37.227Z
I use the same class in the link as in the js in ("#idOfYourDiv"). The console shows no reaction. jquery is now in the head installed.
I have come quite some way with the website using html, css and use bits of code from the web and adapt it for my use. I tried to keep it as simple as possible but this task seems to be an overdrive at the moment.
analog junkie
CC BY-SA 3.0
2018-01-29T15:56:22.957Z
OK, one step further. I think I found out which class you meant and now I have a reaction. It says "POST ...site-url...jquery... 400 (bad Request)". It gives me the alert 5 times?
analog junkie
CC BY-SA 3.0
2018-01-29T16:11:35.057Z
If I open up the alert it says: 
send @ jquery-1.12.4.min.js:4
ajax @ jquery-1.12.4.min.js:4
(anonymous) @ lehrende_index:145
dispatch @ jquery-1.12.4.min.js:3
r.handle @ jquery-1.12.4.min.js:3
Is that any help?
Which div do I call in the middle of the js where you wrote ("#idOfYourDiv")?
analog junkie
CC BY-SA 3.0
2018-01-29T19:01:53.977Z
Please include the newest version of jquery (we are at 3.x you use 1.2). You are not very used to explain errors are you?^^" the important part after you clicked the button is your network tab. As soon as you click it there should be a new row - when this is red it means there was a mistake in the communication between server and client -> the route is wrong. If it's black/normal the communication is OK. Please tell me the color and the text in response/preview tab when you click at it. Your button needs the class `load-instrument` the ID of the pop-up div must be inserted after the ajax part
Robin Schambach
CC BY-SA 3.0
2018-01-29T19:03:03.027Z
If your project is already online and can be accessed you can as well give me the data. This work all in all doesn't take longer than 1 minute
Robin Schambach
CC BY-SA 3.0
2018-01-29T19:15:24.760Z
In my head it says jquery version 3.3.1. 
The url is: http://tonart.srv13.ideefix.net/lehrende_index
analog junkie
CC BY-SA 3.0
2018-01-29T19:21:36.977Z
`Der CSRF-Token konnte nicht überprüft werden.` that means you enabled `csrf` token validation in your config, thus you have to include it in your request as well.  See the documentation here https://craftcms.com/support/csrf-protection for testing purposes you might want to turn it off for the next few minutes in order to test the result without protection
Robin Schambach
CC BY-SA 3.0
2018-01-29T19:31:13.423Z
I turned off the csrf validation.
analog junkie
CC BY-SA 3.0
2018-01-29T19:36:53.280Z
I am also working on a "register" page with the contact-form plugin. That's why csrf was turned on.
analog junkie
CC BY-SA 3.0
2018-01-29T19:41:12.187Z
Da sich das bis zu dieser Länge eh keiner mehr durchlesen wird können wir auch weiter deutsch schreiben, denke das ist einfacher. Dein CSRF token ist immernoch auf enabled und nicht auf `false` entweder du hast den Eintrag nicht in den `Environment` variablen gesetzt oder etwas anderes ist schief gelaufen. Außerdem erhöht der Token nicht unbedingt die Sicherheit deiner Seite sondern schützt nur vor Cross Domain Requests. Wie auch immer.. das hier wird nur ein endloses hin und her hast du Skype oder Hangouts? Wenn du willst kannst du mir auch FTP Zugang geben, dann dürfte es in 10min durch sein
Robin Schambach
CC BY-SA 3.0
2018-01-29T20:21:43.180Z
Gut, dann antworte auf meine mail bitte
Robin Schambach
CC BY-SA 3.0
2018-01-27T09:53:03.697Z
2018-01-27T10:00:39.600Z
2018-01-27T10:00:39.600Z
Robin Schambach
<p>I have created an infinite loop by crossreferencing two includes to each other. On one page. My aim is to load pop up layers on a page (teachers and instruments) and have links to each other.</p>

<pre><code>{#      include: _layer_instrument      #}
&lt;a   href="javascript:void(0)" onclick = 
"document.getElementById('{{teacher}}').style.display='block'; 
document.getElementById('fade').style.display='block'"&gt;
                        {{ teacher.title }}&lt;/a&gt; 
{% include "includes/_layer_teacher" %} 

{#     include: _layer_teacher         #}
&lt;a   href="javascript:void(0)" onclick = 
"document.getElementById('{{instrument}}').style.display='block'; 
document.getElementById('fade').style.display='block'"&gt;
                        {{ instrument.title }}&lt;/a&gt; 
{% include "includes/_layer_instrument" %}  
</code></pre>

<p>Is it possible to use ajax to not load the includes until they are needed?</p>

<ajax>
load include not until its needed
# load include not until its needed

(Asked by: username_0 on 2018-01-27)

I have created an infinite loop by crossreferencing two includes to each other. On one page. My aim is to load pop up layers on a page (teachers and instruments) and have links to each other.
{#      include: _layer_instrument      #}

                        {{ teacher.title }} 
{% include "includes/_layer_teacher" %} 

{#     include: _layer_teacher         #}

                        {{ instrument.title }} 
{% include "includes/_layer_instrument" %}  

Is it possible to use ajax to not load the includes until they are needed?

**Tags:** ajax


---

## 1 answers

### Answer by username_1 on 2018-01-27. Score: 2 | Accepted answer

You can create a custom plugin with Pluginfactory.io and check the box for Controllers but leave the name blank. Copy the downloaded files into your path/to/craft/craft/plugins/>>nameofyourplugin< directory and install it in your cp. 
Then you'll insert a function like this in your controller
public function actionRenderTemplate(){
    $id = craft()->request->getParam('id');
    // do some checks if the id is valid or not here...

    $html = '';
    $success = false;
    $message = '';

    if($entry = craft()->entries->getEntryById($id)){
        // as example to render different templates based on entry type
        $entryType = $entry->getType()->handle; 
        $html = craft()->templates->render('path/to/your/template/' . $entryType, array(
            'entry' => $entry
        ));
        if($html){
            $success = true;
        }
    }else{
        $message = Craft::t('could not find entry with id ' . $id);
    }

    $this->returnJson([
        'message'   => $message,
        'success'   => $success,
        'html'      => $html
    ]);
}

And your Javascript could be this 
$('.load-instrument').click(function(){
    var data = {
        action: "pluginname/actionRenderTemplate",
        id: $(this).data('id')
    };
    $.ajax({
        type: "post",
        url: '',
        data: data,
        success: function(data){
            if(data.success === true){
                $("#idOfYourDiv").html(data.html);
            }else{
                // display error messages here
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            console.log("Status: " + textStatus);
        }
    });
});

However I would recommend you to read the docs about Controllers and about templates to fully understand what you have to do here
edit: your html could be 
Click me

> **Comments:**
> **username_0**: Thanks Robin! Wow! Let's see if I get this sorted.  
> **username_1**: Just tell me if you have any questions. If it's totally new to you and you can't solve something we can go to the chat as well.  
> **username_0**: Yes, it is definitely above my level of skills. How do I implement the plugin into the site and how does it load the include?  
> **username_1**: Unfortunately you can't use the chat yet (you need 20 reputation points) so we have to stay here until you got them. I provided a few links, the question how to implement the plugin is explained in the first one. Create a new folder in your `craft/plugins` directory and set the name of the folder how you named the plugin in pluginfactory.io (all lower case) and copy the downloaded files. In your cp you have settings -> plugins you'll need to install the plugin there. As for the include, you won't have an include anymore since you'll load your template in your controller and not in twig anymore  
> **username_0**: Making and installing the plugin was fine. Now I need to fiddle how to get the template to work. How do i call the id in the plugin, like I did it in the "onclick"-script (document.getElementById('{{teacher}}') to get the right data from craft I am calling in the for loop.  I am very fresh to building websites, so I am leaning out of the window a lot (as one would say in german ;-)) and I am very grateful for your help.  
> **username_1**: https://craftcms.com/docs/plugins/controllers#posting-to-controller-actions thats your `data` variable in javascript `var data = {         action: "pluginname/actionRenderTemplate",         id: $(this).data('id')     };` the `action` attribute defines the routing path, so you'll insert `yourPluginHandle/actionRenderTemplate` In case you are not able to make it work, please tell me your handle and the name of your controller class. I suggest you to read the links I posted  
> **username_1**: I created a "test" once for another user with a full working example of a javascript request here https://github.com/Anubarak/usernotifications you can see a template https://github.com/Anubarak/usernotifications/blob/master/templates/entries/entrytypes/shortMessage.twig a Controller https://github.com/Anubarak/usernotifications/blob/master/controllers/UsernotificationsController.php#L36 and the javascript to communicate https://github.com/Anubarak/usernotifications/blob/master/resources/js/java.js#L2  
> **username_0**: I think the controller class is "TonartLayersController" and the plugin Name is "tonartlayers".  
> **username_1**: So your action parameter will be `tonartLayers/renderTemplate` and the ID - of course - the Id of the teacher or instrument you want to display. Do you have any issues?  
> **username_0**: Sorry, I can't bring it to work and I don't really understand much of what I am doing here. So it is hard for me to look for the missing bits and pieces. I guess I will leave it for now and come back to it when I have more time and know more about php and javascript.  
> **username_1**: Well you need to communicate what is working and what parts are causing trouble. We can't provide any help if you just say "it does not work" otherwise you won't solve your problem.  
> **username_0**: Well the link doesn't react when clicked. Does it need to be a "button" in order to call the plugin?  
> **username_1**: Do you attach the jquery event properly? Did you even include the Javascript part I posted? Is there something in your network tab in your browser console or in your browser console at all? Any errors? It does not matter if it is a link or a button, hell even a div works  
> **username_0**: I included the javascript directly into the html with a <script> tag. I am not sure, which bit was the jquery? I also tried the html you provided.  
> **username_0**: The browser-dev-tool shows the markup but no reaction.  
> **username_1**: Not the cleanest way but it should work. Did you include jquery in your head? https://www.w3schools.com/jquery/jquery_get_started.asp. It's not about what your browser displays, it's about your console. Please press F12 and open the "console" tab, then refresh the page you'll see runtime errors there. Make sure your link has the correct class so you bind the click event. If this little task is far to much for your maybe you should think about if creating a website is a little bit too much at this moment. You should start with small tasks if you have absolutely no clue what's going on  
> **username_0**: I use the same class in the link as in the js in ("#idOfYourDiv"). The console shows no reaction. jquery is now in the head installed. I have come quite some way with the website using html, css and use bits of code from the web and adapt it for my use. I tried to keep it as simple as possible but this task seems to be an overdrive at the moment.  
> **username_0**: OK, one step further. I think I found out which class you meant and now I have a reaction. It says "POST ...site-url...jquery... 400 (bad Request)". It gives me the alert 5 times?  
> **username_0**: If I open up the alert it says:  send @ jquery-1.12.4.min.js:4 ajax @ jquery-1.12.4.min.js:4 (anonymous) @ lehrende_index:145 dispatch @ jquery-1.12.4.min.js:3 r.handle @ jquery-1.12.4.min.js:3 Is that any help? Which div do I call in the middle of the js where you wrote ("#idOfYourDiv")?  
> **username_1**: Please include the newest version of jquery (we are at 3.x you use 1.2). You are not very used to explain errors are you?^^" the important part after you clicked the button is your network tab. As soon as you click it there should be a new row - when this is red it means there was a mistake in the communication between server and client -> the route is wrong. If it's black/normal the communication is OK. Please tell me the color and the text in response/preview tab when you click at it. Your button needs the class `load-instrument` the ID of the pop-up div must be inserted after the ajax part  
> **username_1**: If your project is already online and can be accessed you can as well give me the data. This work all in all doesn't take longer than 1 minute  
> **username_0**: In my head it says jquery version 3.3.1.  The url is: http://tonart.srv13.ideefix.net/lehrende_index  
> **username_1**: `Der CSRF-Token konnte nicht überprüft werden.` that means you enabled `csrf` token validation in your config, thus you have to include it in your request as well.  See the documentation here https://craftcms.com/support/csrf-protection for testing purposes you might want to turn it off for the next few minutes in order to test the result without protection  
> **username_0**: I turned off the csrf validation.  
> **username_0**: I am also working on a "register" page with the contact-form plugin. That's why csrf was turned on.  
> **username_1**: Da sich das bis zu dieser Länge eh keiner mehr durchlesen wird können wir auch weiter deutsch schreiben, denke das ist einfacher. Dein CSRF token ist immernoch auf enabled und nicht auf `false` entweder du hast den Eintrag nicht in den `Environment` variablen gesetzt oder etwas anderes ist schief gelaufen. Außerdem erhöht der Token nicht unbedingt die Sicherheit deiner Seite sondern schützt nur vor Cross Domain Requests. Wie auch immer.. das hier wird nur ein endloses hin und her hast du Skype oder Hangouts? Wenn du willst kannst du mir auch FTP Zugang geben, dann dürfte es in 10min durch sein  
> **username_1**: Gut, dann antworte auf meine mail bitte  

---

