Laravel 8 Ajax Post Request Example Tutorial with Validation

Throughout this laravel Ajax post request you will learn how to send a Ajax Post Request in Laravel 8 application. You can send the errors messages or success message from your backend and show in frontend.

Sending ajax request you need to add routes, one method which return your request from backend and a ajax request which your send from your js file. Let’s start Ajax request in laravel 8 php application step by step easy way.

Step 1. Create Model and Migration

First you need to create model and migration using following command.

php artisan make:model Contact -m

After running the above command you get two files one is model and another is migration.

Now open the database\migrations\2020_09_14_120412_create_contacts_table.php file and update the below code on it;

<?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_number');
            $table->string('subject');
            $table->text('message');
            $table->timestamps();
        });
    }

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

Next, open the app\Models\Contact.php file and update fillable properties same like below.

<?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_number', 'subject', 'message'
    ];
}

Step 2. Add Routes

Now you need to add two methods in your routes/web.php file. One for showing the form and another store and send request from controller. So, open the routes\web.php file and update the below code on it;

<?php

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

Route::get('contact', [ ContactController::class, 'create' ]);
Route::post('contact', [ ContactController::class, 'store' ]);
 
Route::get('/', function () {
    return view('welcome');
});

Step 3. Update Method in Controller

Next, you need to create a new controller using the following command;

php artisan make:controller ContactController

After successfully created controller, Now open the app\Http\Controllers\ContactController.php file and 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('contact');
  }

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

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

      return response()->json(['success'=>'Contact form submitted successfully']);
  }
}

Step 4. Create Blade File

Next, you need to add a blade file contact.blade.php in your resources/views directory. After that open the resources\views\contact.blade.php file and put the below code on it.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Ajax Post Request Example</title>
    <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="contactform">
            <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">
                <label>Subject:</label>
                <input type="text" name="subject" class="form-control" placeholder="Enter subject">
                <span class="text-danger" id="subjectError"></span>
            </div>

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

Step 5. Send Ajax Request

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

<script>
    function submitForm() {
      let name = $("input[name=name]").val();
      let email = $("input[name=email]").val();
      let subject = $("input[name=subject]").val();
      let mobile_number = $("input[name=mobile_number]").val();
      let message = $("textarea[name=message]").val();
      let _token   = $('meta[name="csrf-token"]').attr('content');

      $.ajax({
        url: "/contact",
        type:"POST",
        data:{
          name:name,
          email:email,
          subject:subject,
          mobile_number:mobile_number,
          message:message,
          _token: _token
        },
        success:function(response) {
          console.log(response);
          if(response) {
            $('.success').text(response.success);
            $("#contactform")[0].reset();
          }
        },
        error:function (response) {
          console.log(response.responseJSON.errors);
          $('#nameError').text(response.responseJSON.errors.name);
          $('#emailError').text(response.responseJSON.errors.email);
          $('#subjectError').text(response.responseJSON.errors.subject);
          $('#mobileNumberError').text(response.responseJSON.errors.mobile_number);
          $('#messageError').text(response.responseJSON.errors.message);
        }
       });

    }
</script>

Learn Also: Laravel AJAX CRUD Example Tutorial from Scratch

Now, the ajax request in laravel is completed. Hope its work for your, if you have any question let me know in comment. Follow us on twitter for more updated.

Leave a Comment