makerequest ajax,How to make a POST Ajax request with Symfony and Jquery

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)

Click me

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值