Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly return html template from ajax request with Symfony

I was wondering how to return correctly an HTML template (SEO friendly) from an ajax call.

In my app, I use 2 differents ways to return response:

For simple template:

public function ajaxCallAction() {
//.....
    $response = array(
        "code"      => 202, 
        "success"   => true,
        "simpleData" => $simpleData
    );

    return new JsonResponse($response); 
}

And in the JS I do something like:

$("div#target").click(function(event) {
    $.ajax({
        type: "POST",
        success: function(response) {
            if(response.code === 202 && response.success) {
                $("div#box").append(response.simpleData);    
            }
        }
    });
});

For complexe template (more than 20 lines and various var):

public function ajaxCallAction() {
    //...
    $listOfObjects = $repo->findAll(); 
    $viewsDatas = [
        'listOfObjects' => $listOfObjects,
        //....other vars
    ];

    return $this->render('myAppBundle:template:complexTemplate.html.twig', $viewsDatas);

    //in complexTemplate.html.twig, I loop on listOfObjects for example...
}

And for this kind of call, the JS looks like:

$("div#target").click(function(event) {
    $.ajax({
        type: "POST",
        success: function(response) {
            $("div#box").append(response);    
        }
    });
});

All those methods are working, but with the second one, we dont have status code (does it matter?) and I know that returning directly formated html template can be heavy (according to for example this topic Why is it a bad practice to return generated HTML instead of JSON? Or is it?).

How are you guys doing ajax calls? What are the best practices here?

like image 949
skytorner Avatar asked Sep 02 '25 16:09

skytorner


1 Answers

In my apps, I typically use something like that:

$response = array( 
"code" => 200,
"response" => $this->render('yourTemplate.html.twig')->getContent() );

Hope this help!

Edit

To return your response, you should use JsonResponseas explained in docs: http://symfony.com/doc/current/components/http_foundation.html#creating-a-json-response

Simply use that:

return new JsonResponse($response);
like image 180
Isaac Bosca Avatar answered Sep 04 '25 16:09

Isaac Bosca