Laravel 10/9 Ajax Post Request Example Tutorial


Laravel 10/9 ajax post request with csrf token example; Through this tutorial, you will learn how to submit or post form data on controller using ajax post request with csrf token laravel apps.

Laravel 10/9 Ajax Post Request Example Tutorial

Follow the following steps for how to submit form data using ajax post request with csrf token in laravel apps:

  • Step 1 – Download Laravel Application
  • Step 2 – Setup Database with App
  • Step 3 – Create Contact us Model & Migration
  • Step 4 – Create Contact us Routes
  • Step 5 – Create Contact us Controller By Artisan Command
  • Step 6 – Create Contact us form in Blade File
  • Step 7 – Run Development Server

Step 1 – Download Laravel Application

First of all download or install laravel new setup. So, open terminal and type the following command to install new laravel app into your machine:

composer create-project --prefer-dist laravel/laravel LaravelAjax

Step 2 – Setup Database with App

In this step, setup database with your downloded/installed laravel app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Create Contact us Model & Migration

In this step, open again your command prompt. And run the following command on it. To create model and migration file for form:

php artisan make:model Contact -m

After that, open create_contacts_table.php file inside FormValidation/database/migrations/ directory. And the update the function up() with following code:

    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->text('message');
            $table->timestamps();
        });
    }

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

Step 4 – Create Contact Us Routes

In this step, open web.php file from routes direcotry. And update the following routes into web.php file:

use App\Http\Controllers\AjaxContactController;

Route::get('ajax-form', [AjaxContactController::class, 'index']);
Route::post('store-data', [AjaxContactController::class, 'store']);

Step 5 – Create Contact us Controller By Artisan Command

In this step, run the following command on command prompt to create controller file:

php artisan make:controller AjaxContactController

After that, go to app/http/controllers and open AjaxContactController.php file. And update the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contact;


class AjaxContactController extends Controller
{
    public function index()
    {
        return view('ajax-contact-us-form');
    }

    public function store(Request $request)
    {
        
        $validatedData = $request->validate([
          'name' => 'required',
          'email' => 'required|unique:employees|max:255',
          'message' => 'required'
        ]);

        $save = new Contact;

        $save->name = $request->name;
        $save->email = $request->email;
        $save->message = $request->message;

        $emp->save();

        return redirect('form')->with('status', 'Ajax Form Data Has Been validated and store into database');

    }
}

Step 6 – Create Contact Us Form in Blade File

Now, Go to resources/views and create ajax-contact-us-form.blade.php. Then create one contact us form with name, email and message fields.

We have created an ajax contact us form, so, you can update the following code into ajax-contact-us-form.blade.php file:

<!DOCTYPE html>
<html>
<head>
<title>Laravel 10/9 Ajax Post Request for Submit Form with Csrf token and jQuery Validation</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<style>
.error{
color: #FF0000; 
}
</style>
</head>
<body>
<div class="container mt-4">
<div class="card">
<div class="card-header text-center font-weight-bold">
<h2>Laravel 9 Ajax Post Form Data on Controller with jQuery Validation Example</h2>
</div>
<div class="card-body">
<form name="contactUsForm" id="contactUsForm" method="post" action="javascript:void(0)">
@csrf
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" id="name" name="name" class="form-control">
</div>          
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" id="email" name="email" class="form-control">
</div>           
<div class="form-group">
<label for="exampleInputEmail1">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
</div>
</div>	
<script>
if ($("#contactUsForm").length > 0) {
$("#contactUsForm").validate({
rules: {
name: {
required: true,
maxlength: 50
},
email: {
required: true,
maxlength: 50,
email: true,
},  
message: {
required: true,
maxlength: 300
},   
},
messages: {
name: {
required: "Please enter name",
maxlength: "Your name maxlength should be 50 characters long."
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},   
message: {
required: "Please enter message",
maxlength: "Your message name maxlength should be 300 characters long."
},
},
submitHandler: function(form) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').html('Please Wait...');
$("#submit"). attr("disabled", true);
$.ajax({
url: "{{url('store-data')}}",
type: "POST",
data: $('#contactUsForm').serialize(),
success: function( response ) {
$('#submit').html('Submit');
$("#submit"). attr("disabled", false);
alert('Ajax form has been submitted successfully');
document.getElementById("contactUsForm").reset(); 
}
});
}
})
}
</script>
</body>
</html>

The following below jQuery and ajax code will validate form data before submitting/posting form data on the controller in laravel:

<script>
if ($("#contactUsForm").length > 0) {
$("#contactUsForm").validate({
rules: {
name: {
required: true,
maxlength: 50
},
email: {
required: true,
maxlength: 50,
email: true,
},  
message: {
required: true,
maxlength: 300
},   
},
messages: {
name: {
required: "Please enter name",
maxlength: "Your name maxlength should be 50 characters long."
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},   
message: {
required: "Please enter message",
maxlength: "Your message name maxlength should be 300 characters long."
},
},
submitHandler: function(form) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').html('Please Wait...');
$("#submit"). attr("disabled", true);
$.ajax({
url: "{{url('store')}}",
type: "POST",
data: $('#contactUsForm').serialize(),
success: function( response ) {
$('#submit').html('Submit');
$("#submit"). attr("disabled", false);
alert('Ajax form has been submitted successfully');
document.getElementById("contactUsForm").reset(); 
}
});
}
})
}
</script>

Step 7 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/ajax-form

Recommended Laravel Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?