I'm having a hard time trying to make an ajax request through my CI form having the csrf token enabled. I've been doing a long research and I came up with the same solution is posted in every issue related with this one which is adding the token val to the serialized data in the ajax request. I did this in my ajaxSetup, I get the token but still experiencing the same issue.. Here is my code.
我很难通过启用了csrf令牌的CI表单来尝试发出ajax请求。我一直在做长时间的研究,并且我想出了与此相关的每个问题都发布了相同的解决方案,即将令牌val添加到ajax请求中的序列化数据。我在我的ajaxSetup中做了这个,我得到了令牌,但仍然遇到了同样的问题..这是我的代码。
//AJAX Setup
$.ajaxSetup({
data:{
csrf_test_name: $("input[name='csrf_test_name']").val()
}
});
//Function ajax login
$("form#login").on("submit", function(e){
var $this = $(this);
var mensaje = $("div.msglogin");
$.ajax({
type: "POST",
url: $this.attr("action"),
data: $this.serialize(),
beforeSend: function() {
mensaje.html('<p><img src="public/frontend/img/miniloader.gif"><span><small> Iniciando..</small></span></p>');
}
})
.done (function(data){
console.log($this.serialize());
if(data == "redirect"){
window.location.replace($("input#baselogin").val());
}else{
mensaje.html(data);
}
})
e.preventDefault();
});
This is what I get when I console.log $this.serialize() which means the token is being send
这是我在console.log $ this.serialize()时得到的,这意味着正在发送令牌
csrf_test_name=4a4d6eb47fc8f0c8e932b3b56a4eb9c5&usuario=dan&password=meaannn
Any help will be appreciated.
任何帮助将不胜感激。
1 个解决方案
#1
4
Add the CSRF token to your data
option before posting:
在发布之前将CSRF令牌添加到您的数据选项:
$.ajax({
type: "POST",
url: $this.attr("action"),
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',/*....your data....*/},
beforeSend: function() {
mensaje.html('<p><img src="public/frontend/img/miniloader.gif"><span><small> Iniciando..</small></span></p>');
}
})
The CSRF token needs to be sent with each request so it should be specified by the data. The echo
statement does this. You can add this separately and serialize, but I've shown what you are missing.
CSRF令牌需要随每个请求一起发送,因此应该由数据指定。 echo语句就是这样做的。您可以单独添加和序列化,但我已经显示了您缺少的内容。
#1
4
Add the CSRF token to your data
option before posting:
在发布之前将CSRF令牌添加到您的数据选项:
$.ajax({
type: "POST",
url: $this.attr("action"),
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',/*....your data....*/},
beforeSend: function() {
mensaje.html('<p><img src="public/frontend/img/miniloader.gif"><span><small> Iniciando..</small></span></p>');
}
})
The CSRF token needs to be sent with each request so it should be specified by the data. The echo
statement does this. You can add this separately and serialize, but I've shown what you are missing.
CSRF令牌需要随每个请求一起发送,因此应该由数据指定。 echo语句就是这样做的。您可以单独添加和序列化,但我已经显示了您缺少的内容。