0
votes

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>
3
Maybe your csrf_token change each time you submit? I had this problem before. It's caused by my session not "sticking". Try console.log({{csrf_token()}}) it should stay the same each time you refresh the page.theminer3746

3 Answers

1
votes

Are u sure that each time that is send in ajax?

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

or in plain javascript:

     document.getElementById("cform").reset();
0
votes
 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');
    
    });