I am developing a web application using the Framework Lumen. I looked everywhere, I tried everything but I couldn't find a solution to my problem..
I have a form that I want to validate with jQuery using ajax() with POST
. I tried to use csrf_token
, but always without success.
VIEW :
<form id="form">
<div class="form-group">
<input type="text" class="form-control" name="test" placeholder="Test">
</div>
<button type="button" class="btn btn-primary btn-block valide">Submit</button>
</form>
JS :
$('.valide').click(function () {
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: '/testAjax',
dataType: 'JSON',
data : form.serialize()
}).done(function (data) {
// done
}).fail(function () {
// fail
});
});
routes.php :
$app->post('/testAjax', function () {
return 'I am here';
});
Normally I would get the message "I am here", but instead, I get the following error (Please note that if I make the same request using GET
, it works very well):
POST http://localhost/testAjax 500 (Internal Server Error)
How to make an ajax POST
request using Lumen?
change the route
$app->post('/testAjax', function () {
return 'I am here';
});
to
$app->post('testAjax', function () {
return 'I am here';
});
I found the solution. Simply add the following code to the HTML form, allowing the user to be associated to the current form. This is described in the documentation.
VIEW :
<form id="form">
<!-- Added the following line -->
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<div class="form-group">
<input type="text" class="form-control" name="test" placeholder="Test">
</div>
<button type="button" class="btn btn-primary btn-block valide">Submit</button>
</form>
Also if someone would not send jQuery POST via form you can simply add to your script code below:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Remember to include this html inside your view:
<meta name="csrf-token" content="{{ csrf_token() }}">