Hello Devs,
In this tutorial, we are going to learn laravel 7 ajax form with validation.
Follow this step by step guide given below:
Step 1:
Create Model and Migration
php artisan make:model Post -m
/database/migrations/2020_02_03_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');
}
}
app/Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Run the migrations.
*
* @return void
*/
protected $fillable = ['title','body'];
}
Step 2:
Create Route routes/web.php
Route::get('ajax-form-submit', 'PostController@index');
Route::post('save-form', 'PostController@store');
Step 3:
Create Controller
php artisan make:controller PostController
Step 4:
Controller Code 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)
{
$validator = \Validator::make($request->all(), [
'title' => 'required',
'body' => 'required',
]);
if ($validator->passes()) {
Post::create($request->all());
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
}
Step 5:
Create a blade view 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>Laravel 7 Ajax Form Validation - rathorji.in</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>
</head>
<body class="bg-dark">
<div class="container">
<div class="row mt-5">
<div class="col-md-6 mt-3 offset-md-3">
<div class="card">
<div class="card-header">
<h6>laravel 7 Ajax Form Validation - rathorji.in</h6>
</div>
<div class="card-body">
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<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>
$(document).ready(function() {
$("#send_form").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var title = $("input[name='title']").val();
var body = $("textarea[name='body']").val();
$.ajax({
url: "/save-form",
type:'POST',
data: {_token:_token, title:title, body:body},
success: function(data) {
if($.isEmptyObject(data.error)){
alert(data.success);
}else{
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
</html>
Step 6:
Start Server
php artisan serve
Open this URL:
http://localhost:8000/ajax-form-submit
I hope this example helps you.