Laravel 10 Ajax Form Submit with Validation Example

Laravel 10 Ajax Form Submit with Validation Example

If you are creating a form in Laravel and you want to submit/send/post your form data to the controller and inserted it in the database without refreshing the whole web page in laravel apps. And also you want to validate form data using jquey ajax on the web page.

So, In this tutorial, you will learn how to submit/post/send form data using Ajax with jQuery validation on controller in Laravel 10 apps.

Laravel 10 Ajax Form Submit with Validation Example

By using these steps, you can submit/post/send form data to controller using ajax with jQuery validation (client side) in Laravel 10; is as follows:

  • Step 1 – Setup New Laravel 10 Application
  • Step 2 – Configure Database with App
  • Step 3 – Create a File For the Model & Migration
  • Step 4 – Add Routes
  • Step 5 – Create Controller File
  • Step 6 – Create Blade View File
  • Step 7 – Run Development Server

Step 1 – Setup New Laravel 10 Application

First of all, start your terminal to download or install Laravel 10 new setup. Execute the following command into it to install new Laravel 10 app into your system:

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

Step 2 – Configure Database with App

In this step, Configure your database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

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

Step 3 – Create a File For the Model & Migration

In this step, open again your command prompt. And run the following command on it. To create model and migration file for form:

php artisan make:model Contact -m

After that, open create_contacts_table.php file inside FormValidation/database/migrations/ directory. And the update the function up() with following code:

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

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

Step 4 – Add Routes

In this step, Visit your routes directory and open web.php file in any text editor. And add the following routes into web.php route file:

use App\Http\Controllers\AjaxContactController;

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

Step 5 – Create Controller File

In this step, execute the following command on terminal/command prompt/command line to create controller file for your laravel applications; is as follow:

php artisan make:controller AjaxContactController

After that, go to app/http/controllers and open AjaxContactController.php file. And update the following code into it:

<?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'
        ]);

        $data = $request->all();
        $check = Contact::insert($data);
        $arr = array('msg' => 'Something goes to wrong. Please try lator', 'status' => false);
        if($check){ 
        $arr = array('msg' => 'Successfully submitted form using ajax in laravel', 'status' => true);
        }
        return Response()->json($arr);

    }
}

Step 6 – Create Blade View File

Now, Go to resources/views and create ajax-contact-us-form.blade.php. Then create one contact us form with name, email and message fields.

We have created an ajax contact us form, so, you can update the following code into ajax-contact-us-form.blade.php file:

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 10 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 10 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>

The following below jQuery and ajax code will validate form data before submitting/posting form data on the controller in laravel:

<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')}}",
    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>

Step 7 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/ajax-form

Recommended Laravel Posts

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *