I am not good in js. As mentioned here https://symfony.com/doc/current/http_cache/form_csrf_caching.html I need an ajax code to load symphony csrf on form. Can someone write one for me or give link where I can find one?
I searched google and found this post on stack overflow which addresses the part of fetching the csrf from the service.
From there you need to create a controller action that returns the csrf as a response. Once the controller action is created you would call it in JavaScript using xml http request. If you are using jQuery you can easily use jQuery.ajax() to perform the request to the server side to fetch the csrf.
I had seen that post before posting here. That post shows how to generate csrf and returns it. I need the second part of the work how to fetch it with jQuery. Can you or someone write the jQuery code to fetch it for me?
EDIT: My code is below:
$formFactory = Forms::createFormFactoryBuilder()
->addExtension(new CsrfExtension($csrfManager))
->getFormFactory();
$defaultFormTheme = 'bootstrap_3_layout.html.twig';
$vendorDir = realpath(__DIR__.'/../vendor');
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
$vendorTwigBridgeDir = dirname($appVariableReflection->getFileName());
$viewsDir = realpath('twig');
$twig = new Twig_Environment(new Twig_Loader_Filesystem(array(
$viewsDir,
$vendorTwigBridgeDir.'/Resources/views/Form',
)));
$formEngine = new TwigRendererEngine(array($defaultFormTheme), $twig);
$twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader(array(
TwigRenderer::class => function () use ($formEngine, $csrfManager) {
return new TwigRenderer($formEngine, $csrfManager);
},
)));
$twig->addExtension(new FormExtension());
$translator = new Translator('en');
$twig->addExtension(new TranslationExtension($translator));
$form = $formFactory->createBuilder()
->add('task', TextType::class)
->add('dueDate', DateType::class)
->getForm();
$request = Request::createFromGlobals();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
print_r($data);
}
$twig->display('new.html.twig', array(
'form' => $form->createView(),
));
Then in my form template I have:
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
$.ajax({
url: "app.php",
type: 'POST',
data: {
form: {
_token: "{{ csrf_token('form') }}"
}
},
});
</script>
</head>
<body>
{{ form_start(form, {'method': 'POST', 'action': 'app.php'}) }}
{{ form_row(form.task, {'required': false}) }}
<input type="submit" />
{{ form_end(form, {'render_rest': false}) }}
When I look at my source code I see:
<script>
$.ajax({
url: "app.php",
type: 'POST',
data: {
form: {
_token: "Kf1IK4uikxPCxfmjUkDa8vhRiNI4PWS2zdnTIiWyHC4"
}
},
});
</script>
<form name="form" method="post" action="app.php">
<div class="form-group"><label class="control-label" for="form_task">Task</label><input type="text" id="form_task" name="form[task]" class="form-control" value="qqq" /></div>
<input type="submit" />
</form>
So token is generated but when I do print debug, I don’t see _token is posted. What wrong I did?
Well it seems strange to me that the URL in the ajax request is /app.php. That most certainly seems incorrect. You want to GET the token from a server-side script which part of a controller action. After the page loads you will need to execute an ajax request to fetch the token and replace the value for the csrf token field in the form.
This is standalone script. So naming /app.php is out of question. Can you fix my issue how to fetch csrf with ajax and post it with the form?
Why are you using a stand alone script? Is it that you don’t understand the bundle / MVC architecture of Symfony? In modern web applications there should *typically only be a single entry point. You would then map routes to different controller actions.
Ok. But at this time please help for my main question. How should be the ajax code to fetch csrf and post it with form to the script? What is wrong in my code?
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.