Laravel 7 Ajax Form Validation

10-Apr-2023

.

Admin

Laravel 7 Ajax Form Validation

Hi Guys,

Are you looking for example of laravel 7 ajax form submit with validation. you can understand a concept of ajax form submit with validation in laravel 7. if you want to see example of laravel 7 ajax form submit with validation then you are a right place. you can understand a concept of ajax submit form after validation in laravel 7.

In this tutorial,i will shows how you can submit the form using ajax with jquery validation(Client side) in laravel 7. we can ajax submit form after validation in laravel 7. 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 7 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_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');

}

}

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

{

/**

* Run the migrations.

*

* @return void

*/

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)

{

$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

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>Laravel 7 Ajax Form Validation - 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>

</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 - nicesnippets.com</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>

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...

#Laravel 7

#Laravel