phpicoder Dec 17, 2021 laravel

Hi Developer, In this tutorial we will learn jquery ajax post request example in laravel web applications, in this example we will make simple code for get and add data without page refreshing.

Follow the steps below to understand how to use an Ajax request in Laravel and you will learn how to use an Ajax request in your Laravel application.

Now we go to step by step

Step 1: Create Routes for Ajax

Ajax need a route Now go to routes/web.php and then follow below route. 

Route::post('ajaxRequest', 'AjexCntroller@ajaxRequest');
Route::post('ajaxPostRequest', 'AjexCntroller@ajaxPostRequest');

Step 2: Create Controllers

after create route we crerate cntroller name app/Http/Controllers/AjexCntroller.php and follow below code. 

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
  

class HomeController extends Controller
{

    public function ajaxRequest(Request $request)
    {

        return view('users.createUsers');

    }

    public function ajaxRequestPost(Request $request)
    {

        $input = $request->all();
        DB::table('users')->insert($input);
        return response()->json([
                                'status'=>true,
                                'msg'=>'Got Simple Ajax Request.'
                            ]);

    }
}

Step 3: View File

Now after create controiller go to "resources/views/" path and create user folder and this folder under create createUsers.blade.php file.

open "resources/views/users/createUsers.blade.php" this file and edit following code

The jquery Ajax function requires a jquery file before it can be executed, so include jquery.min.js first and then generate the jquery code.

Example for submit event:

<!DOCTYPE html>
<html>
<head>

    <title>Laravel JQuery Ajax Post Request Example</title>
    <meta charset="utf-8">
    <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 JQuery Ajax Post Request Example</h1>
        <form id="AddUser">
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="name" class="form-control" placeholder="Enter Name" required="">
            </div>

            <div class="form-group">
                <strong>Email:</strong>
                <input type="email" name="email" class="form-control" placeholder="Enter Email" required="">
            </div>

            <div class="form-group">
                <label>Password:</label>
                <input type="password" name="password" class="form-control" placeholder="Enter Password" required="">
            </div>

            <div class="form-group">
                <button class="btn btn-success btn-submit">Add</button>
            </div>
        </form>
    </div>
</body>

<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $("body").on("submit", "#AddUser", function (event) {
        event.preventDefault();

        $.ajax({
            type: "POST",
            url: '{!!route('ajaxPostRequest')!!}',
            data:new FormData(this),
            dataType:'JSON',
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                alert(data.msg);
            }
        });
    });
</script>
</html>

Example for click event:

<!DOCTYPE html>
<html>
<head>

    <title>Laravel JQuery Ajax Post Request Example</title>
    <meta charset="utf-8">
    <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 JQuery Ajax Post Request Example</h1>
        <form>
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="name" class="form-control" placeholder="Enter Name" required="">
            </div>

            <div class="form-group">
                <strong>Email:</strong>
                <input type="email" name="email" class="form-control" placeholder="Enter Email" required="">
            </div>

            <div class="form-group">
                <label>Password:</label>
                <input type="password" name="password" class="form-control" placeholder="Enter Password" required="">
            </div>

            <div class="form-group">
                <button class="btn btn-success btn-submit" id="add_user">Add</button>
            </div>
        </form>
    </div>
</body>

<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $("body").on("click", "#add_user", function (event) {
        event.preventDefault();

        var name = $("input[name=name]").val();
        var email = $("input[name=email]").val();
        var password = $("input[name=password]").val();

        $.ajax({
           type:'POST',
           url:'/ajaxRequest',
           data:{name:name, email:email, password:password},
           success:function(data){
              alert(data.msg);
           }
        });
    });
</script>
</html>
I hope this tutorial help for you.