Laravel Laravel 7

Laravel 7 Ajax Form Validation

Pinterest LinkedIn Tumblr

Step 1: Install Laravel 7 Project

I am going to install a laravel project using composer.

composer create-project --prefer-dist laravel/laravel laravel7

Step 2: Going inside of project using the command

cd laravel7

Step 3: Setup MySQL database

Now, configure this database in the .env file.

 DB_CONNECTION=mysql
 DB_HOST=127.0.0.1
 DB_PORT=3306
 DB_DATABASE=laravel7
 DB_USERNAME=root
 [email protected]

Step 4: Route Setup

Here I am going to create routes to get and post method. now open “routes/web.php” file and put below code.

routes/web.php

Route::get('form-submit','[email protected]');
Route::post('form-submit','[email protected]');

Step 5: Create Controller

Here I am going to create a new controller as FormController. you can check code below.

php artisan make:controller FormController

app/Http/Controllers/FormController.php

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use Validator;
     
class FormController extends Controller
{
     
    /**
     * Display a listing of the form.
     *
     * @return \Illuminate\Http\Response
     */
    public function form()
    {
    	return view('form');
    }
     
    /**
     * Display a listing of the formPost.
     *
     * @return \Illuminate\Http\Response
     */
    public function formPost(Request $request)
    {
     
    	$validator = Validator::make($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email',
            'address' => 'required',
        ]);
     
        if ($validator->passes()) {
            return response()->json(['success'=>'Added new records.']);
        }
     
        return response()->json(['error'=>$validator->errors()->all()]);
    }
}

Step 6: Create View File

Here I am going to create form.blade.php(resources/views/form.blade.php) for layout and check code below.

resources/views/form.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 7 Ajax Validation Real Programmer </title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
       
<div class="container">
    <h1>Laravel 7 Ajax Validation Real Programmer</h1>
       
    <div class="alert alert-danger print-error-msg" style="display:none">
        <ul></ul>
    </div>
       
    <form>
        {{ csrf_field() }}
        <div class="form-group">
            <label>First Name:</label>
            <input type="text" name="first_name" class="form-control" placeholder="First Name">
        </div>
       
        <div class="form-group">
            <label>Last Name:</label>
            <input type="text" name="last_name" class="form-control" placeholder="Last Name">
        </div>
       
        <div class="form-group">
            <strong>Email:</strong>
            <input type="text" name="email" class="form-control" placeholder="Email">
        </div>
       
        <div class="form-group">
            <strong>Address:</strong>
            <textarea class="form-control" name="address" placeholder="Address"></textarea>
        </div>
       
        <div class="form-group">
            <button class="btn btn-success btn-submit">Submit</button>
        </div>
    </form>
</div>
       
<script type="text/javascript">
       
    $(document).ready(function() {
        $(".btn-submit").click(function(e){
            e.preventDefault();
       
            var _token = $("input[name='_token']").val();
            var first_name = $("input[name='first_name']").val();
            var last_name = $("input[name='last_name']").val();
            var email = $("input[name='email']").val();
            var address = $("textarea[name='address']").val();
       
            $.ajax({
                url: "{{ route('my.form') }}",
                type:'POST',
                data: {_token:_token, first_name:first_name, last_name:last_name, email:email, address:address},
                success: function(data) {
                    if($.isEmptyObject(data.error)){
                        alert(data.success);
                    }else{
                        printErrorMsg(data.error);
                    }
                }
            });
       
        }); 
       
        function printErrorMsg (msg) {
            $(".print-error-msg").find("ul").html('');
            $(".print-error-msg").css('display','block');
            $.each( msg, function( key, value ) {
                $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
            });
        }
    });
</script>
</body>
</html>

Now you can open bellow URL on your browser:

php artisan serve

open bellow URL on your browser:

http://localhost:8000/form-submit

Write A Comment