skip to Main Content

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?

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. Try with "renderView" 😉

    return $this->json([
       'html' => $this->renderView('template.html.twig', []),
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search