Codeigniter csrf token with ajax request (500 internal server error)

南楼画角 提交于 2019-12-06 07:06:05

问题


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.

//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

csrf_test_name=4a4d6eb47fc8f0c8e932b3b56a4eb9c5&usuario=dan&password=meaannn

Any help will be appreciated.


回答1:


Add the CSRF token to your data option before posting:

 $.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.



来源:https://stackoverflow.com/questions/25043070/codeigniter-csrf-token-with-ajax-request-500-internal-server-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!