I need to store some map parameter in my symfony project, to do this i need to implement some Ajax in my view which will be able to pass some info to the controller.
I r
I was looking the entire internet and didn't find any solution to similar problem. But i found it-> I had neither issue with the controller, nor the javascript/jquery/ajax nor the security issues. It was in .... wait for it.... in HTML. i had to add type="button" into html tag, otherwise whole page was refreshing. 4 hours wasted on debugging purposes.. but lessons learned.
How to debug problems? 1. Check if ajax is sending post and matching post route on the client side. Firefox -> f12 -> network -> watch the POST events 2. Check the symfony profiler (very usefull tool!) on the -> /app_dev.php/ (dev enviroment) -> Get Request/Response submenu end take last 10, if You see the POST route check closely if its return code and parameters (you wont see response, if its set other than HTML response) 3. In your controller do some action that can be checked if the script inside this route was executed. If so, and You see no response its either on the server side (controller) or client side (twig/ajax/html) 4. Code examples:
Button in html (this was my issue)
Ajax in html or other included js file:
function aButtonPressed(){
$.post('{{path('app_tags_sendresponse')}}',
{data1: 'mydata1', data2:'mydata2'},
function(response){
if(response.code === 200 && response.success){
alert('success!');
}
else{
alert('something broken');
}
}, "json");
}
Now.. server side. Controller:
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class JsonApiController extends Controller
/**
* @Route("/api/programmers")
* @Method("POST")
*/
public function sendResponse()
{
if(isset($_POST['data1'])){
$json = json_encode(array('data' => $_POST['data1']), JSON_UNESCAPED_UNICODE);
file_put_contents("test.json", $json);
return new JsonResponse($json);
}
return new Response('didn't set the data1 var.');
}
}
File put contents
create new file in web directory. If it was matched and file is created that means, that You matched the route, but didn't get the response