1

Form validation with Jquery Ajax in Laravel 8

 1 year ago
source link: https://www.laravelcode.com/post/form-validation-with-jquery-ajax-in-laravel-8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Form validation with Jquery Ajax in Laravel 8

  3113 views

  9 months ago

Laravel

Laravel is a great website application framework providing many functionality in-built. Laravel also provides simple validation and error response. But if you want to use Ajax form request, then you have to do it in another way.

In this article,  we will create new Laravel application from scratch. Then we will create Ajax form submit with validation. Simply follow the steps to create form with ajax request submit with validation.

Step 1 : Laravel project setup

First open the Terminal and go to the folder where you want to create the Laravel project. Then use the bellow command to create the Laravel project.

composer create-project laravel/laravel laravelcode

This will create Laravel project. Now create database and set this database credentials in .env file in the root folder of the project.

Step 2: Create Controller, Routes and View

Go to the project folder in Terminal and create controller class to handle route.

php artisan make:controller ArticleController

Now open routes/web.php file and add new two routes.

<?php

Route::get('form',[ArticleController::class, 'index'])->name('form');
Route::post('form-submit',[ArticleController::class, 'store'])->name('formSubmit');

Now in the ArticleController class add these two new methods:
index() method for view load and store() method for form submit.

<?php

namespace App\Http\Controllers;

use Validator;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    /**
     * Show the form.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('index');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'slug' => 'required',
            'keywords' => 'required',
            'content' => 'required',
        ]);
        
        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()->all()
            ]);
        }

        // your article save codes here...

        return response()->json([
            'success' => 'Article created successfully'
        ]);
    }
}

Now create resources/views/index.blade.php view file.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Ajax Form submit</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
    <div class="container">
        <div class="alert alert-danger" style="display:none"></div>
        <form>
            {{ csrf_field() }}
            <div class="form-group">
                <label>Title</label>
                <input type="text" name="title" class="form-control" placeholder="Enter Title" id="title">
            </div>
            <div class="form-group">
                <label>Slug</label>
                <input type="text" name="slug" class="form-control" placeholder="Enter Slug" id="Slug">
            </div>
            <div class="form-group">
                <label>keywords</label>
                <input type="text" name="keywords" class="form-control" placeholder="Enter keywords" id="keywords">
            </div>
            <div class="form-group">
                <label>Content</label>
                <textarea name="content" class="form-control" placeholder="Enter keywords" id="keywords"></textarea>
            </div>
            <div class="form-group">
                <button class="btn btn-success" id="submit">Submit</button>
            </div>
        </form>
    </div>
    <script type="text/javascript">
         $(document).ready(function(){
            $('#submit').click(function(e) {
                e.preventDefault();
                
                var _token = $("input[name='_token']").val();
                var title = $("input[name='title']").val();
                var slug = $("input[name='slug']").val();
                var keywords = $("input[name='keywords']").val();
                var content = $("textarea[name='content']").val();
                $.ajax({
                    url: "{{ route('formSubmit') }}",
                    method: 'POST',
                    data: {
                        _token : _token,
                        title: title,
                        slug: slug,
                        keywords: keywords,
                        content:content
                    },
                    success: function(data) {
                        if(!$.isEmptyObject(data.error)) {
                            alert('Post created successfully.');
                        } else {
                            $('.alert-danger').empty();
                            $.each(data.errors, function(key, value) {
                                $('.alert-danger').show();
                                $('.alert-danger').append('<p>'+value+'</p>');
                            });
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>

That's it. Now all the validator errors will display when form submitted. I hope you likes this small article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK