I used csrf protection in my web
every time i do ajax call i update the csrf token that sended by controller
everything is working fine
my code :
var csrfName = '<?= csrf_token() ?>',
csrfHash = '<?= csrf_hash() ?>';
$(function() {
$.ajax({
url: "/categories/get",
type: 'post',
dataType: 'json',
data: {
[csrfName]: csrfHash,
},
success: function(result) {
// update csrf token
csrfName = result.csrfName;
csrfHash = result.csrfHash;
// my code ..
},
error: function(xhr, type, error) {
console.log(error);
}
});
$.ajax({
url: "/services/get",
type: 'post',
dataType: 'json',
data: {
[csrfName]: csrfHash,
},
success: function(result) {
// update csrf token
csrfName = result.csrfName;
csrfHash = result.csrfHash;
// my code ..
},
error: function(xhr, type, error) {
console.log);
}
});
But when do ajax call on submit event it showed 403 (forbidden),
Code :
// Form Order
$("form#form-order").submit(function(e) {
e.preventDefault();
let user = $("input[name=user_id]").val();
let service = $("input[name=service_id").val();
let data = $("input[name=data]").val();
let quantity = $("input[name=quantity]").val();
$.ajax({
url: "/orders/new",
type: "post",
data: {
user_id: user,
service_id: service,
data: data,
quantity: quantity,
[csrfName]: csrfHash,
},
success: function(result) {
// update csrf token
csrfName = result.csrfName;
csrfHash = result.csrfHash;
// my code ..
},
error: function(xhr,type,error) {
console.log(error);
},
});
});
i always updated csrf token every time i do ajax call
and also, my form doesn't have an action and method attribute to make sure the form isn't submitted and makes the csrf token change
Or this is because variable scope?
please help!