Render template into Symfony2 with ajax

First, your ajaxAction() should be a bit different as far as I know.

For me this works:

    $template = $this->forward('AcmeDemoBundle:Plugin:another.html.twig')->getContent();

    $json = json_encode($template);
    $response = new Response($json, 200);
    $response->headers->set('Content-Type', 'application/json');
    return $response;

The forward() function renders the template and returns the rendered HTML code.

Your JavaScript file should look like this:

$.ajax({
    type: "POST",
    dataType: 'json',
    url: Routing.generate('ajax'),
    async: false //you won't need that if nothing in your following code is dependend of the result
})
.done(function(response){
    template = response;
    $('#your_div').html(template.html); //Change the html of the div with the id = "your_div"                        
})
.fail(function(jqXHR, textStatus, errorThrown){
    alert('Error : ' + errorThrown);
});

You make an AJAX call to the your ajaxAction, which will return the HTML of the template you want to be rendered.

After that you just need to add a <div id="your_div"></div> at the position you want the template to be rendered. This workes perfectly for me.

To mention is that you need to break down the ajax template to just the code that should be shown.

Tags:

Ajax

Symfony