Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-ajax-post-request-example
In this post, you will learn a basic example of a Laravel 8 ajax post request that will help you to submit a post request to your database without refreshing the page. Ajax is helping our user experience that when saving data don't need to refresh the page like the native of saving a record using a form.
In this example, we will create a basic Laravel 8 ajax post with saving/storing a user.
Step 1: Laravel Installation
Before we start we need to install the Laravel 8 application in our local environment. In this example, I'm using XAMPP via Windows. But you want free to use any machine and OS. To your HTDOCS folder run this command:
composer create-project laravel/laravel laravel-ajax-post-example --prefer-dist
Once done above command run the below command to point our Laravel 8 project directory.
cd laravel-ajax-post-example
Step 2: Database Configuration
If your Laravel project is fresh then you need to update your database credentials. Just open the .env file in your Laravel 8 project.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
Step 3: Generate Controller
To generate a controller for our Laravel ajax post example kindly run the following command:
php artisan make:controller UserController
Step 4: Run Migration
Now let's run the migration by the default Laravel 8 installed.
php artisan migrate
Step 5: Setup Controller
Now, we will set up our store()
method for UserController.php to process our Laravel ajax post.
<?php
namespace App\Http\Controllers;
use Response;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function store(Request $request)
{
$data = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required'
]);
$project = User::create($data);
return response()->json(['success'=>'Laravel ajax example is being processed.']);
}
}
Step 6: Setup Routes
See the routes below in this example we are using users' routes.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::resource('users', UserController::class);
Step 7: Setup our Views
In this example, we will use the welcome.blade.php template as a default by the Laravel installed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel 8 Ajax Post Example</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<style type="text/css">
/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */
main > .container {
padding: 60px 15px 0;
}
</style>
</head>
<body class="d-flex flex-column h-100">
<header>
<!-- Fixed navbar -->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Fixed navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</header>
<!-- Begin page content -->
<main class="flex-shrink-0">
<div class="container">
<h1 class="mt-5">Laravel 8 Ajax Post Example by <a href="https://codeanddeploy.com" target="_blank">codeanddeploy.com</a></h1>
<form data-action="{{ route('users.store') }}" method="POST" enctype="multipart/form-data" id="add-user-form">
@csrf
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email">
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" name="password">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
<script src="{{ asset('js/ajax-post.js') }}" defer></script>
</body>
</html>
Step 8: Javascript for Laravel Ajax Post Request
In this section, we need to create a js folder inside public if already existing just skip it then create a javascript file named ajax-post.js.
$(document).ready(function(){
var form = '#add-user-form';
$(form).on('submit', function(event){
event.preventDefault();
var url = $(this).attr('data-action');
$.ajax({
url: url,
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function(response)
{
$(form).trigger("reset");
alert(response.success)
},
error: function(response) {
}
});
});
});
That's it you have an idea how to implement the Laravel 8 ajax post request. I hope it helps.
Don't forget the run the command:
php artisan serve
I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-ajax-post-request-example if you want to download this code.
Happy coding :)
Top comments (0)