Rym Haouachi
Rym Haouachi

Reputation: 21

How to include AJAX in twig with Symfony 3

I am working on a project with symfony 3 and I want to dynamically get a list of users from database by the name of the project they are working on.

This is the controller action: enter image description here

This way it doesn't show anything, it only shows the first user if I write the action this way: enter image description here

Upvotes: 1

Views: 5046

Answers (1)

LeBlobb
LeBlobb

Reputation: 45

If I do understand it right, you have a page where you have an AJAX request which shall return some data already rendered with twig.

What you need to do is:

  1. One controller which returns normal HTML page

  2. A second controller which returns your rendered data same as your first controller does, but this one uses a template which contains only the HTML which will be returned by the AJAX request.

  3. In your AJAX request call the route defined in the second controller and display the result.

Example1:

ControllerOne.php:

class ControllerOne extends Controller
{
    /**
     * @Route("/")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
        // show your page
        return $this->render('index.html.twig');
    }
}

ControllerTwo.php:

class ControllerTwo extends Controller
{
    /**
     * @Route("get/data/{userId}")
     * @param $userId
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function getDataAction($userId)
    {
        // get some data
        $em = $this->getDoctrine()->getManager();

        // this example shows retrieving user data
        // implement your logic for retrieving projecty by user id here
        $userData = $em->getRepository('AppBundle:User')->findOneBy(array('id' => $userId));

        return $this->render('user.data.html.twig', array('user' => $userData));
    }
}

index.html.twig:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script type="application/javascript">

        // call the controller to get the rendered data
        $.ajax({
            url: "/get/data/1"
        })
                .done(function( data ) {
                    // insert data into div
                    $("#myDiv").html(data);
                });
    </script>
</body>
</html>

user.data.html.twig:

<div>
    <p>
        <!-- you have access to the data passed from controller here -->
        User name: {{user.name}}
    </p>
</div>

Example2:

JsonResponseController.php:

class JsonResponseController extends Controller
{
    /**
     * @Route("get/data/{userId}")
     * @param $userId
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function getDataAction($userId)
    {
        // get some data
        $em = $this->getDoctrine()->getManager();

        // this example shows retrieving user data
        // implement your logic for retrieving projecty by user id here
        $userData = $em->getRepository('AppBundle:User')->findOneBy(array('id' => $userId));

        return new JsonResponse(array('userData' => $userData));
    }
}

Upvotes: 1

Related Questions