I am trying to wrap my brain around what the best is for using an Ajax request and appending it to the dom.
So far I have tried the following:
with jQuery I made a function ‘renderFields’ - that handles the data
in the controller I render a twig view and ‘return this’.
Both have their challenges. Let me start with the twig setup:
because I only need to load a partial of the page I create a seperate twig file for the piece of html that I would like to render. This will increase the amount of twig files.
Even dough I see the data (html) is sending back (console.log) - I still get an error in stead of success.
The jQuery cons:
In the bottom of the twig file I add this ‘renderFields’ method. This is different from page to page - due to the needs. This will increase the amount of data (server-side).
It is hard to make nested statements in a ‘append()’ function. For example I can’t figure out how to loop trough results in the following:
Building nested DOM elements this way is cumbersome. You may want to look into a javascript framework such as Vue, which makes it far easier to create dynamic web pages.
If you want to stick with jQuery for now, try splitting the elements into seperate variables, e.g.:
var i, j, $item, $col, $title, $p;
for(i=0; i<items.length; i++) {
var $item = $('<div class="item"></div>');
var $col = $('<div class="col-md-12"></div>');
$item.append($col);
var $title = $('<h5></h5>').text(item[i].title);
$col.append($title);
for (j = 0; j < items.nodes.length; j++) {
$p = $('<p></p>').text(item.nodes[j]);
$item.append($p);
}
$('#list').append($item);
}
If you will try to render / return the response there is an error. Even when you are not return anything of the method.
BTW: a normal (very large string) is not a problem.