1

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}

johnyT
  • 59
  • 11

1 Answers1

1

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.

Najki
  • 514
  • 6
  • 22
  • i know but this function name is only for test now. So when I create a method saveCoordinatesAction in my MapController, then how should look my var url in javascript? I tried to used "map/saveCoordinatesAction ", "map/saveCoordinates", ""app_dev.php/map/saveCoordinatesAction ", and other combinations but this request stil not reaches, not come to my php function in this controller – johnyT Apr 07 '17 at 11:01
  • mam POST http://localhost/googlemap/web/app_dev.php/saveCoordinatesAction 404 (Not Found), szczerze jestem nowy w symfony kilka godzin temu postawiłem projekt, żeby się nauczyć i te rutingi mnie jescze trochę mylą, wcześniej używałem np Yii2 framework, gdzie w ogole nie trzeba się martwić o takei sprawy – johnyT Apr 07 '17 at 11:04
  • English will be easier for other people to join our discussion. If your base URL is `http://localhost/googlemap/web/app_dev.php/` then you should use all of this (including `http://` protocol prefix) in the URL which your javascript calls, e.g. `http://localhost/googlemap/web/app_dev.php/saveCoordinates` (`app_dev.php` is optional just don't leave it there on your production server) but you need to define a route for this address in `routing.yml` file just as you did for the `map` URL. – Najki Apr 07 '17 at 11:25
  • You can also check your `dev.log` file to see if this request made from JS hits your app. Also, use `php bin/console debug:router` CLI command to check if your `saveCoordinates` route is defined properly (meaning that it is listed on the output of that command). – Najki Apr 07 '17 at 11:28
  • ok now this function in PHP for test is naming saveAction(), then in route I have: `map_save: path: /map/save defaults: { _controller: AppBundle:Map:save } methods: [POST]` and in js `var url = "map/save";` – johnyT Apr 07 '17 at 11:29
  • and now my error look like POST http://localhost/googlemap/web/app_dev.php/map/save 500 (Internal Server Error), The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller? what this mean my post data is null? – johnyT Apr 07 '17 at 11:31
  • It says that your controller must **return** a response. This means that you don't have a return statement in your controller method. Since your're invoking this address in JS, it probably will be useful to return a JSON so you could do it like this: `return new JsonResponse(['your' => 'response array'], Response::HTTP_OK)` – Najki Apr 07 '17 at 11:35
  • ok i think i understand this now I msut return new response now – johnyT Apr 07 '17 at 11:36
  • ok but how can i got this data, I understand I should do something like `$data = $request->request->get('data'); return new JsonResponse(['your' => $data], Response::HTTP_OK);` but how can I got this data now to save in database? – johnyT Apr 07 '17 at 11:40
  • You should [validate it](http://symfony.com/doc/current/validation.html) and [store it](http://symfony.com/doc/current/doctrine.html) (using doctrine for example) by creating an [entity](http://symfony.com/doc/current/doctrine.html#creating-an-entity-class) with all the mappings and stuff mentioned in the docs and finally you can [persist it](http://symfony.com/doc/current/doctrine.html#persisting-objects-to-the-database). – Najki Apr 07 '17 at 11:43
  • Use json_decode($request->getContent(),true) to access the data. http://stackoverflow.com/questions/9522029/posting-json-objects-to-symfony-2 In the future consider starting a new question for new questions. Better yet, just search the board. – Cerad Apr 07 '17 at 11:50
  • but i now got a null in this response can You try to help me in free time with this? I update all my first post like my current code in project – johnyT Apr 07 '17 at 11:53
  • 2
    ok i used $content = $request->getContent(); instead of $data = $request->request->get('params'); thank You guys for help :)) Have a nice day :)) – johnyT Apr 07 '17 at 11:59