Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Enviar datos ajax al controlador php en symfony2

Hola chicos, soy nuevo en Symfony 2 y no me confunden mucho con el envío de datos con ajax al controlador php en Symfony 2. Quiero crear un proyecto con Google Map, así que creo MapController:

 <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; class MapController extends Controller { /** * @Route("/", name="homepage") */ public function indexAction(Request $request) { // replace this example code with whatever you need return $this->render('map/map.html.twig', [ 'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR, 'contData' => ['lat' => '51.24591334500776', 'lng'=> '22.56967306137085'] ]); } public function saveAction(Request $request) { $data = $request->request->get('params'); return new JsonResponse(['data' => $data], Response::HTTP_OK); } }

luego creo enrutamiento:

 app: resource: '@AppBundle/Controller/' type: annotation map: path: /map defaults: { _controller: AppBundle:Map:index } requirements: page: '\d+' map_save: path: /map/save defaults: { _controller: AppBundle:Map:save } methods: [POST]

así que cuando voy a la ruta:

http://localhost/googlemap/web/app_dev.php/mapa

muestro mi plantilla map.html.twig

allí tengo la función javascipt donde traté de enviar datos ajax a algún controlador:

 marker.addListener("click", function () { //! var http = new XMLHttpRequest(); var url = "map/save"; var params = marker.position.lat(); http.open("POST", url, true); //Send the proper header information along with the request http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.onreadystatechange = function () {//Call a function when the state changes. if (http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params);

Pero tengo NULL en esta respuesta: {"data":null}

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Debe preguntarse qué quiere hacer con estos datos enviados desde JS. Si está relacionado con la función del mapa, entonces la creación de un nuevo método en MapController parece estar bien. Si no está relacionado con los mapas, crear un nuevo controlador podría ser una buena forma de hacerlo.

El nombre del método y el controlador debe ser relevante para lo que está haciendo. Su ejemplo saveData no es tan obvio. Si está guardando coordenadas, puede llamar a este método saveCoordinatesAction y definir una ruta dedicada que solo admita solicitudes POST.

En cuanto a pasar la URL a JS, consulte FOSJsRoutingBundle : le permite generar rutas específicas directamente desde JavaScript.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!