LARAVEL Tutorial


Form Validation Using Ajax And JQuery In Laravel 6


In the previous tutorial, you have learned how to validate form data on the client-side (before submitting the form) using jquery in laravel web applications. And also learn how to validate form fields or data without refresh the whole web page.

In this tutorial, you will learn how to submit a form without refresh the whole web page using ajax and jQuery validate. or how to send data using ajax and jQuery validation in laravel. Here we will use the jQuery library for validating laravel form data before submitting the form in laravel web applications.

In this tutorial, we will create a contact us form and submit the laravel form without refresh the whole web page using ajax and jQuery validation. and We will provide you the link below to download this AjaxFormLaravel web application. You can download this web application using that link.

Laravel Ajax Form Submit Using jQuery Validation Example Tutorial

  • Install Laravel Application
  • Configure Database Detail
  • Create Model and Migration
  • Run Migration
  • Create Routes
  • Generate Controller By Artisan
  • Create Blade View
  • Start Development Server

Install Laravel Application

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel AjaxFormLaravel –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

Create Model and Migration

Next, we need to create a model and migration in your laravel web application using the php artisan make:model model_name -m. So run the following command in your project root directory.

Go to the command prompt

cd/project_root_directory

php artisan make:model Contact -m

after that, go to database/migrations/ and find created migration file and add fields, as you want to in your database table.

Your migration file looks like:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->text('message');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

And go to the app/ directory and find the model file. And add table field name as fillable property:- protected $fillable = ['name', 'email', 'message']; 

Your model file looks like:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    protected $fillable = ['name', 'email', 'message']; 
}

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

..
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
... 

Next, go to command prompt and run the following command:

php artisan migrate
OR
php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

//display contact us form
Route::get('contact-us','ContactFormController@index');

//insert contact us data into mysql database table laravel
Route::post('save-contact','ContactFormController@store');

Generate Controller By Artisan

Now, you need to generate a controller file, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller ContactFormController

We will create 2 methods in this controller file. The first method will work to show the form. And this will be the second method, in this method heme which will get the data in Ajax request, insert this data in MySQL database table.

After that, go to App/Http/Controllers/ directory and find the created ContactFormController file and update the following code into your file:

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Validator,Redirect,Response;
Use App\Contact;
 
class ContactFormController extends Controller
{
    public function index() {
        return view('contact');
    }
 
    public function store(Request $request)
    {
       $arr = array('msg' => 'Retrun false status', 'status' => false);

        request()->validate([
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
        ]);
       
        $check = Contact::create($request->all());
   
        if($check){ 

            $arr = array('msg' => 'Form has been submitted successfully using ajax with validation', 'status' => true);
        }
        return Response()->json($arr);
 
    }
}
 

Create Blade Views

Next, you need to create a blade views file, so go resource/views directory and create the following blade views file.

Go to resource/views/ then create a new file name contact.blade.php and update the following code:

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel Jquery Form Validation Example - w3alert.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
  <style>
   .error{ color:red; } 
  </style>
</head>
 
<body>
 
<div class="container mt-5">
   
    <form id="contact-us-form" method="post" action="javascript:void(0)">
      @csrf

      <div class="form-group">
        <label for="formGroupExampleInput">Name</label>
        <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
        <span class="text-danger">{{ $errors->first('name') }}</span>
      </div>

      <div class="form-group">
        <label for="email">Email Id</label>
        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
        <span class="text-danger">{{ $errors->first('email') }}</span>
      </div>  

      <div class="form-group">
        <label for="message">Message</label>
        <textarea name="message" class="form-control" id="message" placeholder="Please enter message"></textarea>
        <span class="text-danger">{{ $errors->first('message') }}</span>
      </div>

      <div class="form-group">
       <button type="submit" class="btn btn-success" id="btn-send">Submit</button>
      </div>
    </form>
 
</div>
<script>
   if ($("#contact-us-form").length > 0) {
    $("#contact-us-form").validate({
     
    rules: {
      name: {
        required: true,
        maxlength: 50
      },
 
      email: {
        required: true,
        maxlength: 50,
        email: true,
      },  

      message: {
        required: true,
        minlength: 50,
        maxlength: 200,
      },    
    },
    messages: {
       
      name: {
        required: "Please enter name",
        maxlength: "Your last 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",
          minlength: "The message should be accept minimum 50 characters",
          maxlength: "The message should be accept minimum 50 characters",
      },
        
    },
    submitHandler: function(form) {
     $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });

      $('#btn-send').html('Sending..');

      $.ajax({
        url: 'http://localhost/FormValidation/public/save-contact' ,
        type: "POST",
        data: $('#contact-us-form').serialize(),
        success: (response) => {
            this.reset();
            alert(response.msg);
            $("#contact-us-form")[0].reset();
            $('#btn-send').html('Submit');
        },
        error: function(response){
            console.log(response);
        }
      });
    },

   })
  }
</script>
</body>
</html>

In contact.blade.php file, we have included jQuery form validation libraries in the header and also written the jQuery validation rules and ajax form submit logic in the footer.

When the form data is inserted into the database using ajax in laravel web application. After this, if the success is received from the server by the response, then we will alert the success message. And will reset the form data. And if there is an error in response from the server, then, in this case, we will print the error to the console using javascript console.log() function.

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your browser and type the below-given URL into your browser:

http://localhost:8000/contact-us
OR

http://localhost/AjaxFormLaravel/public/contact-us

You can also download laravel ajax form submit with validation without page refresh and reload web application here Download