Form validation with Jquery Ajax in Laravel 6

  2 months ago     Views:  322  
Jitesh Meniya
2 Follows


Laravel is a great website application framework providing many functionality in-built. Laravel also provides simple validation and error response. But if you want to use Ajax form request, then you have to do it in another way.

In this article,  we will create new Laravel application from scratch. Then we will create Ajax form submit with validation. Simply follow the steps to create form with ajax request submit with validation.

Step 1 : Laravel project setup

First open the Terminal and go to the folder where you want to create the Laravel project. Then use the bellow command to create the Laravel project.

composer create-project laravel/laravel hackthestuff

This will create Laravel project. Now create database and set this database credentials in .env file in the root folder of the project.

Step 2: Create Controller, Routes and View

Go to the project folder in Terminal and create controller class to handle route.

php artisan make:controller ArticleController

Now open routes/web.php file and add new two routes.

<?php

Route::get('form','ArticleController@index')->name('form');
Route::post('form-submit','ArticleController@store')->name('formSubmit');

Now in the ArticleController class add these two new methods:
index() method for view load and store() method for form submit.

<?php

namespace App\Http\Controllers;

use Validator;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    /**
     * Show the form.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('index');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'slug' => 'required',
            'keywords' => 'required',
            'content' => 'required',
        ]);
        
        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()->all()
            ]);
        }

        // your article save codes here...

        return response()->json([
            'success' => 'Article created successfully'
        ]);
    }
}

Now create resources/views/index.blade.php view file.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Ajax Form submit</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">
        <div class="alert alert-danger" style="display:none"></div>
        <form>
            {{ csrf_field() }}
            <div class="form-group">
                <label>Title</label>
                <input type="text" name="title" class="form-control" placeholder="Enter Title" id="title">
            </div>
            <div class="form-group">
                <label>Slug</label>
                <input type="text" name="slug" class="form-control" placeholder="Enter Slug" id="Slug">
            </div>
            <div class="form-group">
                <label>keywords</label>
                <input type="text" name="keywords" class="form-control" placeholder="Enter keywords" id="keywords">
            </div>
            <div class="form-group">
                <label>Content</label>
                <textarea name="content" class="form-control" placeholder="Enter keywords" id="keywords"></textarea>
            </div>
            <div class="form-group">
                <button class="btn btn-success" id="submit">Submit</button>
            </div>
        </form>
    </div>
    <script type="text/javascript">
         $(document).ready(function(){
            $('#submit').click(function(e) {
                e.preventDefault();
                
                var _token = $("input[name='_token']").val();
                var title = $("input[name='title']").val();
                var slug = $("input[name='slug']").val();
                var keywords = $("input[name='keywords']").val();
                var content = $("textarea[name='content']").val();
                $.ajax({
                    url: "{{ route('formSubmit') }}",
                    method: 'POST',
                    data: {
                        _token : _token,
                        title: title,
                        slug: slug,
                        keywords: keywords,
                        content:content
                    },
                    success: function(data) {
                        if(!$.isEmptyObject(data.error)) {
                            alert('Post created successfully.');
                        } else {
                            $('.alert-danger').empty();
                            $.each(data.errors, function(key, value) {
                                $('.alert-danger').show();
                                $('.alert-danger').append('<p>'+value+'</p>');
                            });
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>


That's it. Now all the validator errors will display when form submitted. I hope you likes this small article.

Thank you.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments