Laravel 11 Ajax Post Request Example

Laravel 11 Ajax Post Request Example show you how to use ajax request in the Laravel 11 application to save or submit data to the database without refresh.

#1 Install Laravel App

Install a fresh laravel app

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

Next, go inside the app directory

cd laravel-app

#2 Setup Database

Next, open the .env file which is located in your project root directory and update your database credentials.

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

#3 Make Model and Migration

Now generate a model and migration using the below command:

php artisan make:model Contact -m

Next, open the newly created file database\migrations\2020_09_14_120412_create_contacts_table.php and add the required field.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('mobile');
$table->text('message');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contacts');
}
}

Next, we need to run the migrate command to generate database tables.

php artisan migrate

Next, open the app\Models\Contact.php file and add fillable properties in your contact model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
use HasFactory;

protected $fillable = [
'name', 'email', 'mobile', 'message'
];
}

#4 Add Routes

Now, open the routes/web.php file and add the get and post routes for implementing the ajax post request in laravel.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;

Route::get('contacts', [ ContactController::class, 'create' ]);
Route::post('contacts', [ ContactController::class, 'store' ]);


Route::get('/', function () {
    return view('welcome');
});

#5 Create Controller

Now, create a new controller in your application using the following command.

php artisan make:controller ContactController

Next, open the app/Http/Controllers/ContactController.php file and update the below code on it.

<?php

namespace App\Http\Controllers;

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

class ContactController extends Controller
{
    public function create()
    {

      return view('contacts');
    }

   public function store(Request $request)
   {
        
        $request->validate([
            'name'      => 'required',
            'email'     => 'required',
            'mobile'    => 'required',
            'message'   => 'required',
        ]);

        Contact::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'mobile'   => $request->mobile,
            'message'  => $request->message,
        ]);

      return response()->json([ 'success'=> 'Your request successfully submitted!']);
  }
}

#6 Create Blade File

Next, create a new blade file named contacts.blade.php, which shows the form where we send the ajax request for showing form validations and etc functionalities. So, open the resources\views\contacts.blade.php file and update the below code on it

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>

<body>
    <div class="container">
        <h1>Laravel Ajax Post Request Example with <a href="https://codingdriver.com/">Coding Driver</a></h1>
          <span class="success" style="color:green; margin-top:10px; margin-bottom: 10px;"></span>
        <form id="contact-form">
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="name" class="form-control" placeholder="Enter Name">
                <span class="text-danger" id="nameError"></span>
            </div>
            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="email" class="form-control" placeholder="Enter Email">
                <span class="text-danger" id="emailError"></span>
            </div>

            <div class="form-group">
                <strong>Mobile Number:</strong>
                <input type="text" name="mobile" class="form-control" placeholder="Enter Mobile">
                <span class="text-danger" id="mobileError"></span>
            </div>
            <div class="form-group">
                <strong>Message:</strong>
                <input type="text" name="message" class="form-control" placeholder="Enter Your Message">
                <span class="text-danger" id="messageError"></span>
            </div>
            <div class="form-group">
                <button class="btn btn-success save-data">Save</button>
            </div>
        </form>
    </div>
</body>
</html>

#7 Send Ajax Request

After creating the blade file now add the ajax jquery code after the last closing div of your blade file and send the post request to your controller via ajax. Here we are using the jQuery submit function and use the CSRF for send request.

<script>

  $('#contact-form').on('submit', function(event){
      event.preventDefault();

      let name = $("input[name=name]").val();
      let email = $("input[name=email]").val();
      let mobile = $("input[name=mobile]").val();
      let message = $("input[name=message]").val();
      let _token   = $('meta[name="csrf-token"]').attr('content');

      $.ajax({
        url: "/contacts",
        type:"POST",
        data:{
          name:name,
          email:email,
          mobile:mobile,
          message:message,
          _token: _token
        },
        success:function(response){
          console.log(response);
          if(response) {
            $('.success').text(response.success);
            $("#contact-form")[0].reset();
          }
        },
        error: function(error) {
         console.log(error);
          $('#nameError').text(response.responseJSON.errors.name);
          $('#emailError').text(response.responseJSON.errors.email);
          $('#mobileError').text(response.responseJSON.errors.mobile);
          $('#messageError').text(response.responseJSON.errors.message);
        }
       });
  });
</script>

That’s it. Hope this article help you to send the ajax post request in laravel 11.