简体   繁体   English

Laravel csrf 令牌在 ajax 上第二次不匹配

[英]Laravel csrf token mismatch on ajax post a second time

im trying to submit an ajax post in laravel but im having some problem regarding the form's csrf token.我试图在 Laravel 中提交一个 ajax 帖子,但我在表单的 csrf 令牌方面遇到了一些问题。 In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted.在我的表单中,如果我在第一次提交表单时满足了我在 ajax post url 中设置的条件。 However if i submit the form and purposely failed the conditions i set in my ajax post url in the first try, If i submit the form again i get a token mismatch exception in my ajax error log.但是,如果我提交表单并故意使我在第一次尝试时在我的 ajax post url 中设置的条件失败,如果我再次提交表单,我的 ajax 错误日志中会出现令牌不匹配异常。 Do i need to refresh the csrf_token every ajax post?我是否需要在每个 ajax 帖子中刷新 csrf_token?

Below is my code下面是我的代码

JS JS

$(document).on('submit','.registration-form',function(e){
    e.preventDefault();
    var form = $(this);
    var form_url = $(this).attr("action");
    var form_values = $(this).serialize();

    $.ajax({
        url:form_url,
        type:'POST',
        data:form_values,
        dataType: 'json',
        async:false,
        success: function(result){
            console.log(result);
            if(result['status']==true){
                location.href = result['redirect'];
            }
            else{
                form.find(".form-details").show().html(result['message']);
            }
        },
        error: function(ts) {
            console.log(ts.responseText)
        }
    });
});

HTML HTML

<form action="{{ url('login') }}" method="POST" class="registration-form">
    {{ csrf_field() }}
    <input type="text" name="username" class="input" placeholder="Email">
    <input type="password" name="password" class="input" placeholder="Password">
    <button class="button is-redbox is-flat is-fullwidth">Login</button>
</form>

Are u sure that each time that is send in ajax?你确定每次都用ajax发送吗?

data: {
    "_token": "{{ csrf_token() }}",
}
      $("#cform")[0].reset();

或在普通的 javascript 中:

     document.getElementById("cform").reset();
 public function regenerateToken(){
    session()->regenerate();
    return response()->json([
    'msg'=>'success',
    'token'=>csrf_token()
    ]);
    }

   $('#form').submit(funtion(event) {
    event.preventDefault(event);
    // Submit the form using AJAX.
    $.ajax({
    type: 'POST',
    url: form.attr('action'),
    data: formData
    })
    .done(function(response) {
    // Make sure that the formMessages div has the 'success' class.
    if (response.msg === 'success') {
    $('#token').val(response.token);
    console.log($('#token').val());
    }
    }
    $('input[type="text"],input[type="email"] ,textarea, select').val(''); $(this).trigger('reset');
    
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM