Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda