Laravel 6 Ajax Form Submit With Validation Example

Laravel 6 , Laravel

Nicesnippets

26206

02-01-2020


Laravel 6 Ajax Form Submit With Validation Example

Hi Guys,

In this tutorial,i will shows how you can submit the form using ajax with jquery validation(Client side) in laravel 6. we can ajax submit form after validation in laravel 6. you can easy laravel ajax form submit.

you can submit the form using jquery and without the whole page refresh. When we submit an ajax form in laravel, we will add csrf token in ajax request.

here following example to laravel 6 ajax form submit with validation.

Step 1: Create Model and Migration


here this step, we will create one model and migration name Post. Use the below following command and create it

php artisan make:model Post -m

Next,Open post migration file and put the below code.

here 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');

}

}

Next, go to app/Post.php and open post model file and put the below code.

here following path of model fille

Path:/app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

protected $fillable = ['title','body'];

}

Step 2: Create Route

Create two routes one for show form and the second route 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

In this step,we will create a controller. Use the below command for generate controller

php artisan make:controller PostController

Step 4:Controller Code

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

here following path of Controller fille

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\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

In this step, we will create one blade file name ajaxPostForm.blade.php.

In this ajax form, we will implement a jquery submit handler. first, we will validate form using jquery validation and second is to submit an ajax form 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 - nicesnippets.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 - nicesnippets.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>

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

Step 6:Start Server

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

php artisan serve

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

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

It will help you...


Recommended Posts