简体   繁体   中英

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. In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted. 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. Do i need to refresh the csrf_token every ajax post?

Below is my code

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

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

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');
    
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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