Laravel 8 Ajax Form Submit With Validation Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
Laravel 6 Ajax Form Submit With Validation Example

today now in this tutorial,i will share with you how we can submit the form by using ajax with jquery validation(Client side) in laravel 8 application. Here we can see ajax submit form after validation in laravel 8 application. We can do this easily by laravel ajax form submit.

So here we can submit the form by using jquery and also without the whole page refresh. So when we submit an ajax form in laravel application, then we will add csrf token in ajax request.

Now just need to following example to laravel 8 ajax form submit also with validation.

Step 1: Create Model and Migration

Now here in this step, we will create one new model and also migration name Post. By Using the below following command we can create it

php artisan make:model Post -m

So on next,open post migration file and need to put the below code.

Here need to following path of migration file

Path: /database/migrations/2020_01_02_095534_create_posts_table.php

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Now in next, go to app/Model/Post.php and open post model file and put the below code.

here following path of model fille

Path:/app/Model/Post.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title','body'];
}
Step 2: Create Route

Now here need to create two routes one for show form and the second route for send data to the server:

Here following path of route fille

Path:/routes/web.php

Route::get('ajax-form-submit', 'PostController@index');
Route::post('save-form', 'PostController@store');
Step 3:Create Controller

So now in this step,we will create a new controller. By Use the below command for generate controller

php artisan make:controller PostController 
Step 4:Controller Code

here now this step,we will create two methods inside the our new controller first one is index method for used to display contact form and second store method is used to store data in the mysql database

Now just following path of Controller fille

Path:/app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Post;

class PostController extends Controller
{
   
  public function index()
  {
  	return view('ajaxPostForm');
  }

  public function store(Request $request)
  {
     $input = $request->all();
     $request->validate([
       'title' => 'required',
       'body' => 'required'
     ]);
     $check = Post::create($input);
     $arr = array('msg' => 'Something goes to wrong. Please try again lator', 'status' =>false);
     if($check){ 
        $arr = array('msg' => 'Successfully Form Submit', 'status' => true);
     }
    return response()->json($arr);
  }
}
Step 5:Create a blade view

Now in this step, we will create one new blade file name ajaxPostForm.blade.php.

so in this ajax form, we will implement a jquery submit handler. Now first, we will validate form by using jquery validation and second is to submit an ajax form by using submit handler.

here following path of blade fille

Path:/resources/views/ajaxPostForm.blade.php

<!DOCTYPE html>
<html>
<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>Post Form - CodingsPoint.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">
      <div class="row">
         <div class="col-md-6 mt-3 offset-md-3">
            <div class="card">
               <div class="card-header bg-dark text-white">
                  <h6>laravel 6 Ajax Form Submission Example - CodingsPoint.com</h6>
               </div>
               <div class="card-body">
                  <form id="post-form" method="post" action="javascript:void(0)">
                     @csrf
                     <div class="row">
                        <div class="col-md-12">
                           <div class="alert alert-success d-none" id="msg_div">
                                   <span id="res_message"></span>
                              </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <div class="form-group">
                              <label>Title<span class="text-danger">*</span></label>
                              <input type="text" name="title" placeholder="Enter Title" class="form-control">
                              <span class="text-danger p-1">{{ $errors->first('title') }}</span>
                           </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <div class="form-group">
                              <label>Body<span class="text-danger">*</span></label>
                              <textarea class="form-control" rows="3" name="body" placeholder="Enter Body Text"></textarea>
                              <span class="text-danger">{{ $errors->first('body') }}</span>
                           </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <button type="submit" id="send_form" class="btn btn-block btn-success">Submit</button>
                        </div>   
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </div>
</body>
<script>
   if ($("#post-form").length > 0) {
    $("#post-form").validate({
      
    rules: {
      title: {
        required: true,
        maxlength: 50
      },
      body: {
        required: true,
        maxlength: 250
      }
    },
    messages: {
      title: {
        required: "Please Enter Name",
        maxlength: "Your last name maxlength should be 50 characters long."
      },
      body: {
        required: "Please Enter Body",
        maxlength: "Your last body maxlength should be 250 characters long."
      },
    },
    submitHandler: function(form) {
     $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $('#send_form').html('Sending..');
      $.ajax({
        url: '/save-form' ,
        type: "POST",
        data: $('#post-form').serialize(),
        success: function( response ) {
            $('#send_form').html('Submit');
            $('#res_message').show();
            $('#res_message').html(response.msg);
            $('#msg_div').removeClass('d-none');
 
            document.getElementById("post-form").reset(); 
            setTimeout(function(){
            $('#res_message').hide();
            $('#msg_div').hide();
            },10000);
        }
      });
    }
  })
}
</script>
</html>

So now we will validate form data before submit, check validation like mobile number contains only digits not accept any character. And the name filed contains 50 characters only. And we will only use post method in laravel ajax with csrf token

Step 6:Start Server

Now In this step, we will use the php artisan serve command.

php artisan serve

So Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/ajax-form-submit

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →