Laravel 6 Validation + JQuery 3 Ajax Form Submit with form input serialize()

//Laravel 6 Validation + JQuery 3 Ajax Form Submit with form input serialize()
    <title>Ajax Validation in Laravel 6</title>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
   <link rel="stylesheet" href="" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">Ajax Validation in Laravel 6</a>
<div class="container">
    <form id='sign-up' action="{{ URL::to('customValiPost') }}" class="form-horizontal" method="post" novalidate>
        @if (count($errors) > 0)
        <div class="alert alert-danger">
                @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
        <div class="form-group" id="email-div">
            <label class="control-label" for="email">Email</label>
            <input id="email" type="email" placeholder="" title="Please enter you email" required value="" name="email" class="form-control">
                            <span class="help-block">
                                <strong id="form-errors-title"></strong>
            <span class="help-block small">Your email is required</span>
        @if ($errors->has('title'))
        <span class="help-block">
        <strong>{{ $errors->first('title') }}</strong>
        <button class="btn btn-primary">Save</button>
                headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') },
                beforeSend: function( xhr ) {
                        //add some animation
                }).done(function(json) {
                    if (json['status']) {
                        //success refresh
                }).fail(function(xhr, ajaxOptions, thrownError) {
                var _responseText = JSON.parse(xhr.responseText);
                console.warn(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + _responseText['message']);


We put the csrf token in the ajax headers area, so in the ajax data, we can direct post the data.serialize with this, in Laravel Controller we can do validation like usual. If we put the csft token via post data, we need manually define the input name individually when we post to controller.

I hope this tips can help you code better.

By |2019-09-21T10:54:22+00:00September 21st, 2019|Computers and Internet|0 Comments

Leave A Comment