...
Laravel, Tutorials

Laravel form submit using ajax with validation

20 February 2019

Laravel form with ajax

In this example, I am going to show you how to make validation using jquery ajax in laravel 5 application.
We will build a simple ajax validation using Laravel 5.5. Laravel provides an easy way to use validation without ajax but if you want to use Laravel validation with jquery then you can’t do it quickly. The server checks all the input field against defined validation and if any of the validation fails, it will redirect to our create page with error messages.

1)Define route

Create new route for insert contact details in web.php (routes/web.php)

<?php
Route::get('/contact', 'ContactController@create')->name('contact');
Route::post('/contactinsert', 'ContactController@store')->name('contact-insert');
?>

2)Get view page

In this point, now we should create new controller as ContactController. So run bellow command and create new controller.

      php artisan make:controller ContactController -r

After this command you will find new file in this path app/Http/Controllers/HomeController.php. In this controller we will write two methods for ajax view and post as listed bellow methods:
1)create()
2)store()

In this paragraph, most importantly Laravel 5.5 will introduce support for custom validation rule. So Validation objects as an alternative to using Validator::extend for custom validation rules.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use App\Contact;

class ContactController extends Controller {
   
    public function create() {
        return view('contact');
    }
   
    public function store(Request $request) {               
        $validator = Validator::make(
                        $request->all(), [
                            'email' => 'required|email',
                            'name' => 'required|regex:/^[\pL\s\-]+$/u',
                            'message' => 'required',
                        ]
        );
        if ($validator->passes()) {
            $contact = new Contact;
            $contact->name = $request->name;
            $contact->message = $request->message;            
            $contact->email = $request->email;
            $contact->save();                      
            return response()->json(['success'=>'Contact inquiry stored successfully.']);            
        } else {
            return response()->json(['error' => $validator->errors()->all()]);
        }        
    }
}
?>

3)HTML form design with ajax

In Last step, let’s create myform.blade.php(resources/views/contact.blade.php) for layout and we will write design code and jquery ajax code,so put following code:

            <div class="error-msg" style="display:none">
                <ul class="alert"></ul>
            </div>
            <!-- Form -->
            <form action="" method="POST" class="col-sm-8" id="contact_form">
                @csrf
                <!-- Name -->
                <div class="form-name col-md-6">
                    <label>Name</label>
                    <input type="text" name="name" value="{{ old('name') }}">                    
                </div>
                <!-- End Name -->
                <!-- E-Mail -->
                <div class="form-mail col-md-6">
                    <label>E-Mail</label>
                    <input type="email" name="email" value="{{ old('email') }}">                    
                </div>
                <!-- End E-Mail -->
                <!-- Message -->
                <div class="form-text col-md-12">
                    <label>Message</label>
                    <textarea name="message">{{ old('message') }}</textarea>                    
                </div>
                <!-- End Message -->
                <!-- Button -->
                <div class="form-button col-md-12">
                    <button type="submit" name="submit">Send Message</button>
                </div>
                <!-- End Buttom -->
            </form>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#contact_form').on('submit', function (e) {
                    $(".error-msg").css('display', 'none');
                    $(".error-msg").find("ul").removeClass('alert-danger');
                    $(".error-msg").find("ul").removeClass('alert-success');
                    e.preventDefault();
                    $.ajax({
                        type: "POST",
                        url: "{{ route('contact-insert') }}",
                        data: $(this).serialize(),
                        success: function (data) {
                            if ($.isEmptyObject(data.error)) {
                                printMsg(data.success, 'success');
                                $("#contact_form")[0].reset();
                            } else {                    
                                printMsg(data.error, 'error');
                            }
                        }
                    });
                });
                function printMsg(msg, type) {
                    $(".error-msg").find("ul").html('');
                    $(".error-msg").css('display', 'block');
                    if (type == 'error') {
                        $(".error-msg").find("ul").addClass('alert-danger');
                        $.each(msg, function (key, value) {
                            $(".error-msg").find("ul").append('<li>' + value + '</li>');
                        });
                    } else {
                        $(".error-msg").find("ul").addClass('alert-success');
                        $(".error-msg").find("ul").append('<li>' + msg + '</li>');
                        setTimeout(function () {
                            $(".error-msg").find("ul").html('');
                            $(".error-msg").css('display', 'none');
                        }, 3000);
                    }
                }
            });
        </script>

Now we are ready to run our example so run bellow command for quick run:

       php artisan serve

Now you can open bellow URL on your browser:
http://localhost:8000/contact

Leave a Comments