Form Submit using Ajax in Laravel 8 with Validation

Laravel 8 ajax form submit with validation. In this post, i will show from scratch on how to submit form using ajax and validate form data before insert into database.

In this post example, i will create laravel ajax contact form and submit form data using ajax without page reload. As well as validate form data before submit using jQuery validation library.

Note that, in laravel 8, the ajax code will submit form without reloading page laravel 8. If form data successfully validate and insert into database, it will shows success message.

Laravel 8 Ajax Form Submit with Validation

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Configuring Database using Env File
  • Step 3 – Create Model & Migration File For Contact Form
  • Step 4 – Create Routes
  • Step 5 – Creating Controller
  • Step 6 – Create Blade File For Contact Form
  • Step 7 – Start Development Server
  • Step 8 – Run Laravel 8 Ajax Form Submit with Validation App On Browser

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Configuring Database using Env File

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Create Model & Migration File For Contact Form

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaravelAjax

Then create model and migration file by using the following command:

php artisan make:model Contact -m

The above command will create two files into your laravel 8 ajax form submit with validation application, which is located inside the following directories:

  • LaravelAjax/app/Models/Contact.php
  • LaraveljQuery/database/migrations/create_contacts_table.php

So, find create_contacts_table.php file inside LaravelAjax/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('subject');
            $table->text('description');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AjaxContactController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('ajax-contact-form', [AjaxContactController::class, 'index']);
Route::post('save', [AjaxContactController::class, 'store']);

Step 5 – Creating Controller

In step 5, create form controller by using the following command:

php artisan make:controller AjaxContactController

The above command will create AjaxContactController.php file, which is located inside LaraveljQuery/app/Http/Controllers/ directory.

So open AjaxContactController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\Contact;


class AjaxContactController extends Controller
{
    public function index()
    {
        return view('ajax-contact-form');
    }

    public function store(Request $request)
    {

        $contact = new Contact;

        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->subject = $request->subject;
        $contact->description = $request->description;

        $contact->save();

        return response()->json(['success' => true]);

    }
}

Step 6 – Create Blade File For Contact Form

In step 6, create new blade view file that named ajax-contact-form.blade.php inside resources/views directory for ajax contact us form.

And the following jQuery ana ajax code will validate form data on client side or before submit to controller or database in laravel:

<script>
if ($("#ajax-contact-form").length > 0) {
$("#ajax-contact-form").validate({
  rules: {
    name: {
    required: true,
    maxlength: 50
  },
  email: {
    required: true,
    maxlength: 50,
    email: true,
  },
  subject: {
    required: true,
    maxlength: 100
  },  
  description: {
    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",
  },
  subject: {
    required: "Please enter subject",
    maxlength: "Your subject maxlength should be 100 characters long."
  },    
  description: {
    required: "Please enter description",
    maxlength: "Your description 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('save')}}",
    type: "POST",
    data: $('#ajax-contact-form').serialize(),
    success: function( response ) {
      $('#submit').html('Submit');
      $("#submit"). attr("disabled", false);
      alert('Ajax form has been submitted successfully');
      document.getElementById("ajax-contact-form").reset(); 
    }
   });
  }
  })
}
</script>

Don’t worry i have already added the jQuery ajax code to validation form data on client side on blade views.

So, you can add the following php and html form code into ajax-contact-form.blade.php:

<!DOCTYPE html>
<html>
<head>
	<title>Form Submit using Ajax jQuery in Laravel 8 with 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 Form Submit with Validation Example</h2>
    </div>
    <div class="card-body">
      <form name="ajax-contact-form" id="ajax-contact-form" 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">Subject</label>
          <input type="text" id="subject" name="subject" class="form-control">
        </div>      


        <div class="form-group">
          <label for="exampleInputEmail1">Description</label>
          <textarea name="description" id="description" class="form-control"></textarea>
        </div>

        <button type="submit" class="btn btn-primary" id="submit">Submit</button>
      </form>
    </div>
  </div>
</div>	
<script>
if ($("#ajax-contact-form").length > 0) {
$("#ajax-contact-form").validate({
  rules: {
    name: {
    required: true,
    maxlength: 50
  },
  email: {
    required: true,
    maxlength: 50,
    email: true,
  },
  subject: {
    required: true,
    maxlength: 100
  },  
  description: {
    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",
  },
  subject: {
    required: "Please enter subject",
    maxlength: "Your subject maxlength should be 100 characters long."
  },    
  description: {
    required: "Please enter description",
    maxlength: "Your description 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('save')}}",
    type: "POST",
    data: $('#ajax-contact-form').serialize(),
    success: function( response ) {
      $('#submit').html('Submit');
      $("#submit"). attr("disabled", false);
      alert('Ajax form has been submitted successfully');
      document.getElementById("ajax-contact-form").reset(); 
    }
   });
  }
  })
}
</script>
</body>
</html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel 8 form application:

php artisan serve

Step 8 – Run Laravel 8 Ajax Form Submit with Validation App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/ajax-contact-form

When you fire the above given url on browser, you will look like in the following image:

After submit form using ajax with jquery validation in laravel will look like in following image:

Leave a Comment