Laravel 9 Ajax Request Example

10-Apr-2023

.

Admin

Laravel 9 Ajax Request Example

Hi Guys,

In this tutorial, I am going to learn you ajax request example in laravel 9. This example will help you laravel 9 ajax form submit example. step by step explain jquery ajax request laravel 9. you can understand a concept of jquery ajax post laravel 9 csrf.

Ajax request is a basic requirement of any php project, we are always looking for without page refresh data should store in database and it's possible only by jquery ajax request. same thing if you need to write ajax form submit in laravel 9 then i will help you how you can pass data with ajax request and get on controller.

Here I will give you full example for laravel 9 jquery ajax post example. So, let's follow few step to create example of jquery ajax request laravel 9.

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Step 2: Database Configuration

In second step, we will make database Configuration for example database name, username, password etc for ajax form submit example of laravel 9 So lets open .env file and all deatils like as bellow:

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name(blog)

DB_USERNAME=here database username(root)

DB_PASSWORD=here database password(root)

Step 3: Add Migration

we are going to create file upload application for students. so we have to create migration for "students" table using Laravel 9 php artisan command, so first fire bellow command:

php artisan make:migration create_students_table

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create students table.

database/migrations/create_students_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreatestudentsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('students', function (Blueprint $table) {

$table->id();

$table->string('email');

$table->string('password');

$table->text('address');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('students');

}

}

Now you have to run this migration by following command:

php artisan migrate

Step 4: Add Route

Here, we need to add route for ajax form submit. so open your "routes/web.php" file and add following route.

routes/web.php

<?php

use App\Http\Controllers\StudentController;

/*

|--------------------------------------------------------------------------

| 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('ajax/request', [StudentController::class, 'ajaxRequest'])->name('ajax.request');

Route::post('ajax/request/store', [StudentController::class, 'ajaxRequestStore'])->name('ajax.request.store');

Step 5: Add Controller and Model

In this step, now we should create new controller as StudentController. So run bellow command and create new controller. bellow controller for create StudentController.

php artisan make:controller StudentController --model=StudentController

After bellow command you will find new file in this path "app/Http/Controllers/StudentController.php".

In this controller will create two methods as bellow:

1)fileUpload()

2)fileUploadPost()

So, let's copy bellow code and put on StudentController.php file.

app/Http/Controllers/StudentController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Student;

class StudentController extends Controller

{

/**

* Display a listing of the myformPost.

*

* @return \Illuminate\Http\Response

*/

public function ajaxRequest()

{

return view('ajaxExample');

}

/**

* Display a listing of the myformPost.

*

* @return \Illuminate\Http\Response

*/

public function ajaxRequestStore(Request $request)

{

$validator = Validator::make($request->all(), [

'password' => 'required',

'email' => 'required|email',

'address' => 'required',

]);

if ($validator->passes()) {

// Store Data in DATABASE from HERE

return response()->json(['success'=>'Added new records.']);

}

return response()->json(['error'=>$validator->errors()]);

}

}

Ok, so after run bellow command you will find "app/Models/Student.php" and put bellow content in Student.php file:

app/Models/Student.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Student extends Model

{

use HasFactory;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'email', 'password','address'

];

}

Step 6: Add Blade File

In last step. In this step we have to create just blade students. So mainly we have to create ajaxExample file. So finally you have to create one following bellow blade file:

1) ajaxExample.blade.php

So let's just create following file and put bellow code.

resources/views/ajaxExample.blade.php

resources/views/ajaxExample.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

<title>Ajax Request Example Laravel 9</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<style type="text/css">

body{

background:#f2f2f2;

}

.section{

padding:50px;

background:#fff;

}

</style>

</head>

<body>

<div class="container" style="margin-top: 100px;">

<div class="row">

<div class="offset-md-3 col-md-6 section">

<h2>Ajax Request Example Laravel 9</h2>

<div class="alert alert-success alert-block" style="display: none;">

<button type="button" class="close" data-dismiss="alert">×</button>

<strong class="success-msg"></strong>

</div>

<form>

@csrf

<div class="form-group">

<label for="email">Email:</label>

<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">

<span class="text-danger error-text email_err"></span>

</div>

<div class="form-group">

<label for="pwd">Password:</label>

<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="password">

<span class="text-danger error-text password_err"></span>

</div>

<div class="form-group">

<label for="address">Address:</label>

<textarea class="form-control" name="address" id="address" placeholder="Address"></textarea>

<span class="text-danger error-text address_err"></span>

</div>

<button type="submit" class="btn btn-primary btn-submit">Submit</button>

</form>

</div>

</div>

</div>

<script type="text/javascript">

$(document).ready(function() {

$(".btn-submit").click(function(e){

e.preventDefault();

var _token = $("input[name='_token']").val();

var email = $("#email").val();

var pswd = $("#pwd").val();

var address = $("#address").val();

$.ajax({

url: "{{ route('ajax.request.store') }}",

type:'POST',

data: {_token:_token, email:email, pswd:pswd,address:address},

success: function(data) {

printMsg(data);

}

});

});

function printMsg (msg) {

if($.isEmptyObject(msg.error)){

console.log(msg.success);

$('.alert-block').css('display','block').append('<strong>'+msg.success+'</strong>');

}else{

$.each( msg.error, function( key, value ) {

$('.'+key+'_err').text(value);

});

}

}

});

</script>

</body>

</html>

Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/ajax/request

Output :

Store Data Success

I hope it can help you....

#Laravel 9