Home > database >  Send array to javascript from Symfony controller
Send array to javascript from Symfony controller

Time:11-04

I need to send data array from Controller, but i don't know what is the good way. I think the controller should send the array in json. This is my js code:

 $.typeahead({
        input: '[data-autocomplete="team"]',
        minLength: 1,
        order: "asc",
        offset: true,
        hint: true,
        source: {
             items: {
                 data: [here, i need to get array data from controller]
                 ajax: {
                     type: "POST",
                     url: "/teams",
                     data: {
                         myKey: $('[data-autocomplete="team"]').val()
                     }
                 }
             }
         },
    });

and this is my controller

    /**
     * @Route(name="teams", path="/teams")
     */
    public function sendTeams()
    {
        $em = $this->getDoctrine()->getManager();
        $teams = $em->getRepository(Teams::class)->findAll();
        $data = [];
        foreach($teams as $team){
           $data[] = $team->getName();
        }

        return new JsonResponse($data, 200, [], true);
    }

CodePudding user response:

Using a JsonReponse is a proper solution.

But there is multiple way your code could be improved.

If your project is configured with the default autowiring options, you could auto wire your repository (which by the way would have been better if called TeamRepository associated to a Team entity instead of Teams):

/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = [];
    foreach($teams as $team){
       $data[] = $team->getName();
    }

    return new JsonResponse($data, 200, [], true);
}

You should also not set the bool $json parameter of JsonResponse since $data is not a json but an array that you want to be converted into a json. Using a JsonResponse will return a proper JsonResponse with json headers, the bool $json parameter just help converting a php variable into a json (if possible).

/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = [];
    foreach($teams as $team){
       $data[] = $team->getName();
    }

    return new JsonResponse($data);
}

You could also simplify your foreach (The arrow key function is php 7.4 , use a regular callable otherwise):

/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = array_map(fn($e) => $e->getName(), $teams);

    return new JsonResponse($data);
}

It depends of you, but you could also use FOSJsRoutingBundle to not write manually the path to your teams route. You can check how to use it if you want.

  • Related