5. Sử dụng token ajax trong Lavarel (ok)

https://viblo.asia/p/tap-20-validation-laravel-GrLZDWAEKk0

C:\xampp\htdocs\blog\resources\views\create_post.blade.php

<h1>Create new post</h1>
<form action="/post" method="POST">
    @csrf
    <div>
        <p>Title</p>
        <input type="text" name="title">
    </div>
    <div>
        <p>Body</p>
        <textarea name="body" cols="30" rows="10"></textarea>
    </div>
    <br>
    <div>
        <button type="submit">Create</button>
    </div>
</form>
<script src="http://localhost/library/jquery/jquery.min.js"></script>
<script>
    $('form').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: '/post',
            type: 'POST',
            data: {
                _token: $('input[name=_token]').val(),
                title: $('input[name=title]').val(),
                body: $('textarea[name=body]').val()
            }, success: function(res) {
                //
            }, error: function(error) {
                console.log(error);
            }
        })
    })
</script>

C:\xampp\htdocs\blog\app\Http\Controllers\PostController.php

C:\xampp\htdocs\blog\routes\web.php

Last updated

Was this helpful?