How do I post ajax with no form



  • I meet the problem that:
    I make a link for add friend request like: <a href="#" onclick="friends.addFriend(1, 2);">#######</a>

    In Js file, I call an ajax post for adding request to database. But when posting, I found
    TokenMismatchException in VerifyCsrfToken.php line 53:

    How can I post an ajax call without submitting a post form?


  • Global Moderator

    By default for all POST, PUT, or DELETE requests you are required to supply csrf token.
    There's couple ways to go about it, but lets do correct one it this situation.

    Method 1:
    Most obvious would be supply your ajax call with csrf token (chose one of two):

    <form>
    {{ csrf_field() }}
    or
    <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
    </form>
    

    Then you would capture it in your script using name _token:

    var _token = $("input[name='_token']").val();
    

    At this point you want to supply _token variable with your ajax data.

    $.ajax({
    .....
    data: {
         '_token': _token,
    },
    .....
    });
    

    Method 2:
    If you do a lot of ajax work you could rather store token in main layout of your view in meta tag like:
    <meta name="csrf-token" content="{{ csrf_token() }}" />

    And then in your script before you invoke ajax:

    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    

    Now every ajax will include csrf token.

    Also there are other ways to deal with it including removing route from csrf middleware or disabling it all together, but those would be last resort ways. More details on CSRF Protection


Log in to reply