Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
Send array to javascript from Symfony controller

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);
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda