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

//Laravel 6 Validation + JQuery 3 Ajax Form Submit with form input serialize()
<head>
    <title>Ajax Validation in Laravel 6</title>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  
</head>
<body>
<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>
    </div>
</nav>
<div class="container">
    <form id='sign-up' action="{{ URL::to('customValiPost') }}" class="form-horizontal" method="post" novalidate>
        {{csrf_token()}}
        @if (count($errors) > 0)
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
        @endif
 
        <div class="form-group" id="email-div">
            <label class="control-label" for="email">Email</label>
            <input id="email" type="email" placeholder="example@gmail.com" title="Please enter you email" required value="" name="email" class="form-control">
 
                            <span class="help-block">
                                <strong id="form-errors-title"></strong>
                            </span>
            <span class="help-block small">Your email is required</span>
        </div>
                            </span>
        @if ($errors->has('title'))
        <span class="help-block">
        <strong>{{ $errors->first('title') }}</strong>
         </span>
        @endif
        <br/>
        <button class="btn btn-primary">Save</button>
    </form>
    <script>
      
    $(function(){
    
        $('#sign-up').on('submit',function(e){
            $.ajaxSetup({
                headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') },
            });
            e.preventDefault(e);
            $("#title-div").removeClass("has-error");
            $.ajax({
    
                type:"POST",
                url:'/ajax',
                data:$(this).serialize(),
                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']);
    
            });
        });
    });


    </script>
</div>
</body>
</html>

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