johnyT
johnyT

Reputation: 59

Send ajax data to php controller in symfony2

Hi guys I am new in symfony 2 and i have little confusing with sending data with ajax to php controller in symfony 2. I want to create project with google map so i create 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);
    }

}

then i create routing:

    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] 

so when i go to to route:

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

i display my template map.html.twig

there i have javascipt function where i tried to send ajax data to some controller:

    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);

But i have NULL in this response: {"data":null}

Upvotes: 1

Views: 694

Answers (1)

Najki
Najki

Reputation: 544

You need to ask yourself what do you want to do with this data sent from JS. If it's related to map feature then creating a new method in MapController seems fine. If it's not related to maps then creating a new controller could be a good way to go.

Naming of method and controller should be relevant to what you're doing. Your saveData example is not so obvious. If you're saving coordinates then you could name this method saveCoordinatesAction and define a dedicated route supporting POST requests only.

As for passing the URL to JS, check out FOSJsRoutingBundle - it lets you generate specific routes directly from JavaScript.

Upvotes: 1

Related Questions