How to define CSRF token in ajax call in Cakephp 3. Also How CSRF can be off for some ajax requests

后端 未结 3 1093
半阙折子戏
半阙折子戏 2021-01-18 06:46

In Cakephp3 when the Csrf component is enabled. How I can use it in ajax call. In this beforeSend parameter of ajax csrf token is set in header. What is the val

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 06:54

    CakePHP 3

    Please do not unlock fields/disable CSRF security component for any particular action. This is important for the form security.

    for those who are getting "The request has been black-holed." ,"form tampered error", "you are not authorized to access that location." or "unexpected field in POST data". It is mainly due to the CSRF component working as expected.

    Disabling or modifying it is not a solution. Instead of disabling, please follow the right approach. In above case, please try serializing the form and that should do the magic.

    var el = $("#xyzForm");
    
    var ajaxTPCalls = el.serializeArray();
      $.ajax({
                                type: el.attr('method'),
                                async: true,
                                url:  el.attr('action'),
                                data: ajaxTPCalls,
                                dataType: "json",
                                cache: false,
                                success: function (data) {
    
                                    toastr.success(data.message, data.title);
                                },
                                error: function (jqXHR) {
                                    if (jqXHR.status == 403) {
                                        $("body").html(jqXHR.responseText);
                                    }
                                }
                            });
    

    This way you do not disable CSRF or unlock any field.

提交回复
热议问题