How to make a POST Ajax request with Symfony and Jquery How to make a POST Ajax request with Symfony and Jquery symfony symfony

How to make a POST Ajax request with Symfony and Jquery


Try this,

/**                                                                                    * @Route("/ajax", name="_recherche_ajax") */public function ajaxAction(Request $request)    {    if ($request->isXMLHttpRequest()) {                 return new JsonResponse(array('data' => 'this is a json response'));    }    return new Response('This is not ajax!', 400);}

In case of you sending an Ajax request, you need to return json/plaintext/xml data, and not a whole Response object.

PS: Do not forget to add use statment for Request and JsonResponse

EDIT : As the error message you added says, you need to import the annotation @Method by using :

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;


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)

<button name="button" id="button" class="button" type="button" value="100"> Click me </button> 

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