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:
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}