In this tutorial you will learn about the Laravel 8 Ajax Post Form Data With Validation and its application with practical example.
In this Laravel 8 Ajax Post Form Data With Validation tutorial you’ll learn to validate and submit form data without reloading or refreshing of page using ajax.
In this tutorial I’ll show you step by step how to submit and validate form data without reloading or refreshing of page using ajax. Generally Form validation is performed at server side, but can be performed at both the server and client side. In this laravel form validation tutorial we will be learning about laravel server side validations. In this tutorial, I’ll show you how to define laravel validation rules, how to validate form input and to display validation errors using ajax. In Laravel, to submit form data using ajax we must have to incorporate csrf token with form data and set X-CSRF-TOKEN request header with ajax form submit request.
Laravel 8 Ajax Post Form Data With Validation
In this laravel 8 ajax form validation example we will create a contact us form and submit form data on controller using jQuery ajax. We will also validate form data before submit to controller using jQuery validation in laravel. In this step by step tutorial I’ll guide you through the process to submit form using ajax with validation laravel 8. Please follow the steps given below:
- Download Laravel 8 Application
- Setup Database with App
- Create Contact us Model & Migration
- Create Contact us Routes
- Create Contact us Controller By Artisan Command
- Create Contact us form in Blade File
- Run Development Server
Install Laravel 8
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel larablog |
Configure Database In .env file
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=larablog DB_USERNAME=root DB_PASSWORD= |
Create Model & Migration
Now, in this step we will create model and migration file for form. Please run the following command:
1 |
php artisan make:model Contact -m |
Once above command is executed there will be a migration file created inside database/migrations/ directory, just open create_contacts_table.php migration file and update the function up() method as following:
1 2 3 4 5 6 7 8 9 10 |
public function up() { Schema::create('contacts', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->text('message'); $table->timestamps(); }); } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Create Routes
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 |
use App\Http\Controllers\AjaxContactController; Route::get('ajax-form', [AjaxContactController::class, 'index']); Route::post('store-data', [AjaxContactController::class, 'store']); |
Create Contact us Controller
Next, we have to create a controller to display form and to handle form validation and submit operations. Lets Create a controller named AjaxContactController using command given below –
1 |
php artisan make:controller AjaxContactController |
Open the AjaxContactController.php file and put the following code in it.
app/Http/Controllers//AjaxContactController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Contact; class AjaxContactController extends Controller { public function index() { return view('ajax-contact-us-form'); } public function store(Request $request) { $validatedData = $request->validate([ 'name' => 'required', 'email' => 'required|unique:employees|max:255', 'message' => 'required' ]); $save = new Contact; $save->name = $request->name; $save->email = $request->email; $save->message = $request->message; $emp->save(); return redirect('form')->with('status', 'Ajax Form Data Has Been validated and store into database'); } } |
Create Form Blade File
Now, create form blade view file to display form and submit to database. So, Go to resources/views and create ajax-contact-us-form.blade.php and update the following code into it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
<!DOCTYPE html> <html> <head> <title>Laravel 8 Ajax Form using jQuery Validation</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script> <style> .error{ color: #FF0000; } </style> </head> <body> <div class="container mt-4"> <div class="card"> <div class="card-header text-center font-weight-bold"> <h2>Laravel 8 Ajax Post Form Data on Controller with jQuery Validation Example</h2> </div> <div class="card-body"> <form name="contactUsForm" id="contactUsForm" method="post" action="javascript:void(0)"> @csrf <div class="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" id="name" name="name" class="form-control"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email</label> <input type="email" id="email" name="email" class="form-control"> </div> <div class="form-group"> <label for="exampleInputEmail1">Message</label> <textarea name="message" id="message" class="form-control"></textarea> </div> <button type="submit" class="btn btn-primary" id="submit">Submit</button> </form> </div> </div> </div> <script> if ($("#contactUsForm").length > 0) { $("#contactUsForm").validate({ rules: { name: { required: true, maxlength: 50 }, email: { required: true, maxlength: 50, email: true, }, message: { required: true, maxlength: 300 }, }, messages: { name: { required: "Please enter name", maxlength: "Your name maxlength should be 50 characters long." }, email: { required: "Please enter valid email", email: "Please enter valid email", maxlength: "The email name should less than or equal to 50 characters", }, message: { required: "Please enter message", maxlength: "Your message name maxlength should be 300 characters long." }, }, submitHandler: function(form) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#submit').html('Please Wait...'); $("#submit"). attr("disabled", true); $.ajax({ url: "{{url('store-data')}}", type: "POST", data: $('#contactUsForm').serialize(), success: function( response ) { $('#submit').html('Submit'); $("#submit"). attr("disabled", false); alert('Ajax form has been submitted successfully'); document.getElementById("contactUsForm").reset(); } }); } }) } </script> </body> </html> |
Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
http://localhost:8000/ajax-form