Ajax Post Request in Laravel Tutorial Example

Using the Laravel 10 Ajax post request example tutorial you will learn how to add Ajax Request in Laravel with the post method.

Ajax request is a primary requirement of any php or Laravel project, we are always looking for without page refresh data should store in the database and it’s possible only by jquery and Ajax request.

For sending an Ajax request you need to add routes, one method which returns your request from the backend, and an Ajax request which your send from your js file.

1. Add Routes

First, you need to add two methods in your routes web file. One for showing the form and another for storing and sending requests from the controller.

So, open routes\web.php and put the below routes on it:

<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AjaxController;
  
Route::get('ajax-request', [AjaxController::class, 'create']);
Route::post('ajax-request', [AjaxController::class, 'store']);

2. Create Controller & Update Method

Now create a new controller using the following command;

php artisan make:controller AjaxController

After successfully created controller; now you need to update two methods in your controller. So open the app\Http\Controllers\AjaxController.php controller and add the below code on it;

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxController extends Controller
{
    public function create()
    {

      return view('ajax-request');
    }

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

        $data = $request->all();
        #create or update your data here

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

3. Create Blade File

Next, you need to add a blade file ajax-request.blade.php in your resources/views directory. So open resources\views\ajax-request.blade.php file and add 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="ajaxform">
            <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>

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

  $(".save-data").click(function(event){
      event.preventDefault();

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

      $.ajax({
        url: "/ajax-request",
        type:"POST",
        data:{
          name:name,
          email:email,
          mobile_number:mobile_number,
          message:message,
          _token: _token
        },
        success:function(response){
          console.log(response);
          if(response) {
            $('.success').text(response.success);
            $("#ajaxform")[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>

Learn Also: Laravel Form Submit Using Ajax Easy Example

Learn Also: Laravel AJAX CRUD Example Tutorial from Scratch

Now, the ajax request in laravel is completed. Ajax post or get request is the primary requirement of all admin backend or frontend projects. Many begginers don’t know to to send a ajax request from blade to controller without page reload and refresh. We have added a easy and well known code here for you to leaning easy way ajax post request in laravel application. Hope this code work for you and don’t stress so far, if you have any question let me know in comment. Follow us on twitter for more updated.

6 thoughts on “Ajax Post Request in Laravel Tutorial Example”

    • Hi, I think you have OrderAjaxController and this tutorial added AjaxController, so you need to change code according your controller.

      Reply

Leave a Comment