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}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

13 Comments

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
mam POST 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
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.
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).
ok i used $content = $request->getContent(); instead of $data = $request->request->get('params'); thank You guys for help :)) Have a nice day :))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.