AJAX is used to communicate with the server and perform actions like – database manipulation, file upload, etc. without the need to refresh the whole page.
In this tutorial, I show how you can use jQuery AJAX to insert, update, and delete records in Laravel 7.
Contents
1. Table structure
I am using users
table in the example.
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL );
2. Database Configuration
Open .env
file.
Specify the host, database name, username, and password.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=tutorial DB_USERNAME=root DB_PASSWORD=
3. Model
Create a Page
model.
php artisan make:model Page
Here, create 4 methods –
- getuserData – Select all records from
users
table and return it. - insertData – Check if username already exists in
users
table or not. If not then insert the record and return the insertid otherwise return 0. - updateData – Update record according to passed
$id
. - deleteData – Delete record from the
users
table according to passed$id
.
Completed Code
<?php namespace App; use Illuminate\Support\Facades\DB; use Illuminate\Database\Eloquent\Model; class Page extends Model { public static function getuserData($id=null){ $value=DB::table('users')->orderBy('id', 'asc')->get(); return $value; } public static function insertData($data){ $value=DB::table('users')->where('username', $data['username'])->get(); if($value->count() == 0){ $insertid = DB::table('users')->insertGetId($data); return $insertid; }else{ return 0; } } public static function updateData($id,$data){ DB::table('users')->where('id', $id)->update($data); } public static function deleteData($id=0){ DB::table('users')->where('id', '=', $id)->delete(); } }
4. Controller
Create a PagesController
controller.
php artisan make:controller PagesController
Here, create 5 methods –
- index – Load index view.
- getUsers – This method is used to handle the AJAX request. Fetch records by calling
getuserData()
method and assign in$userData['data']
. Return JSON response. - addUser – This method is used to handle AJAX request to insert a new record. Read values and initialize
$data
. CallinsertData
where pass$data
. If record successfully inserted then return insert id otherwise 0. - updateUser – This method is used to handle AJAX request to update record. Read values and initialize
$data
. CallupdateData()
method where pass$editid
and$data
for update record. - deleteUser – This method is used to handle AJAX request to delete a record. Call
deleteUser()
method where pass$id
.
Completed Code
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Page; class PagesController extends Controller { public function index(){ return view('index'); } // Fetch records public function getUsers(){ // Call getuserData() method of Page Model $userData['data'] = Page::getuserData(); echo json_encode($userData); exit; } // Insert record public function addUser(Request $request){ $name = $request->input('name'); $username = $request->input('username'); $email = $request->input('email'); if($name !='' && $username !='' && $email != ''){ $data = array('name'=>$name,"username"=>$username,"email"=>$email); // Call insertData() method of Page Model $value = Page::insertData($data); if($value){ echo $value; }else{ echo 0; } }else{ echo 'Fill all fields.'; } exit; } // Update record public function updateUser(Request $request){ $name = $request->input('name'); $email = $request->input('email'); $editid = $request->input('editid'); if($name !='' && $email != ''){ $data = array('name'=>$name,"email"=>$email); // Call updateData() method of Page Model Page::updateData($editid, $data); echo 'Update successfully.'; }else{ echo 'Fill all fields.'; } exit; } // Delete record public function deleteUser($id=0){ // Call deleteData() method of Page Model Page::deleteData($id); echo "Delete successfully"; exit; } }
5. Route
Open router/web.php
file.
Here, define 5 routes –
- /
- /getUsers – This is get type route use in jQuery AJAX to load records.
- /addUser – This is post type route use in jQuery AJAX to insert a record.
- /updateUser – This is post type route use in jQuery AJAX to update record.
- /deleteUser/{id} – This is get type route use in jQuery AJAX to delete record and it takes one argument.
Completed Code
<?php Route::get('/', 'PagesController@index'); Route::get('/getUsers', 'PagesController@getUsers'); Route::post('/addUser', 'PagesController@addUser'); Route::post('/updateUser', 'PagesController@updateUser'); Route::get('/deleteUser/{id}', 'PagesController@deleteUser');
6. View
Create a new index.blade.php
file in resources/views/
directory.
Download jQuery library and store in public/js/
directory or you can use CDN.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML
Add csrf_token()
in <meta>
and include jQuery library script.
Create <table >
for displaying the user list. Add row in <tbody>
with 3 textboxes and a button for inserting a record with jQuery AJAX.
Script
Read csrf_token
from <meta >
tag and assign in CSRF_TOKEN
variable.
- Fetch records –
Create fetchRecords()
function which called on document ready state.
From here send AJAX GET request to "getUsers"
. On successful callback empty the <tbody>
rows except the first row.
Loop on the response
data and read values. Create new <tr >
and add input element for value edit in <td >
. Also, add update and delete button to send AJAX request on click.
Append new <tr >
in <tbody>
.
- Add record –
On add button click read input values from the first row and send AJAX POST request to "addUser"
where pass CSRF_TOKEN, username, name, and email as data
.
On successful callback if response>0
then add a new row in <tbody >
.
- Update record –
On update button click get the edit id from data-id
and read name and email.
Send AJAX POST request to "updateUser"
where pass CSRF_TOKEN, editid, name, and email as data
.
- Delete record –
On delete button click send AJAX GET request to "deleteUser"
and delete id from data-id
. On successful callback remove the <tr>
.
Completed Code
<!DOCTYPE html> <html> <head> <title>Insert Update and Delete record with AJAX in Laravel</title> <!-- provide the csrf token --> <meta name="csrf-token" content="{{ csrf_token() }}" /> <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> --> <!-- jQuery CDN --> <script src="{{asset('js/jquery-3.3.1.min.js')}}"></script> </head> <body> <table border='1' id='userTable' style='border-collapse: collapse;'> <thead> <tr> <th>Username</th> <th>Name</th> <th>Email</th> <th></th> </tr> </thead> <tbody> <tr> <td><input type='text' id='username'></td> <td><input type='text' id='name' ></td> <td><input type='text' id='email' ></td> <td><input type='button' id='adduser' value='Add'></td> </tr> </tbody> </table> <!-- Script --> <script type='text/javascript'> var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); $(document).ready(function(){ // Fetch records fetchRecords(); // Add record $('#adduser').click(function(){ var username = $('#username').val(); var name = $('#name').val(); var email = $('#email').val(); if(username != '' && name != '' && email != ''){ $.ajax({ url: 'addUser', type: 'post', data: {_token: CSRF_TOKEN,username: username,name: name,email: email}, success: function(response){ if(response > 0){ var id = response; var findnorecord = $('#userTable tr.norecord').length; if(findnorecord > 0){ $('#userTable tr.norecord').remove(); } var tr_str = "<tr>"+ "<td align='center'><input type='text' value='" + username + "' id='username_"+id+"' disabled ></td>" + "<td align='center'><input type='text' value='" + name + "' id='name_"+id+"'></td>" + "<td align='center'><input type='email' value='" + email + "' id='email_"+id+"'></td>" + "<td align='center'><input type='button' value='Update' class='update' data-id='"+id+"' ><input type='button' value='Delete' class='delete' data-id='"+id+"' ></td>"+ "</tr>"; $("#userTable tbody").append(tr_str); }else if(response == 0){ alert('Username already in use.'); }else{ alert(response); } // Empty the input fields $('#username').val(''); $('#name').val(''); $('#email').val(''); } }); }else{ alert('Fill all fields'); } }); }); // Update record $(document).on("click", ".update" , function() { var edit_id = $(this).data('id'); var name = $('#name_'+edit_id).val(); var email = $('#email_'+edit_id).val(); if(name != '' && email != ''){ $.ajax({ url: 'updateUser', type: 'post', data: {_token: CSRF_TOKEN,editid: edit_id,name: name,email: email}, success: function(response){ alert(response); } }); }else{ alert('Fill all fields'); } }); // Delete record $(document).on("click", ".delete" , function() { var delete_id = $(this).data('id'); var el = this; $.ajax({ url: 'deleteUser/'+delete_id, type: 'get', success: function(response){ $(el).closest( "tr" ).remove(); alert(response); } }); }); // Fetch records function fetchRecords(){ $.ajax({ url: 'getUsers', type: 'get', dataType: 'json', success: function(response){ var len = 0; $('#userTable tbody tr:not(:first)').empty(); // Empty <tbody> if(response['data'] != null){ len = response['data'].length; } if(len > 0){ for(var i=0; i<len; i++){ var id = response['data'][i].id; var username = response['data'][i].username; var name = response['data'][i].name; var email = response['data'][i].email; var tr_str = "<tr>" + "<td align='center'><input type='text' value='" + username + "' id='username_"+id+"' disabled></td>" + "<td align='center'><input type='text' value='" + name + "' id='name_"+id+"'></td>" + "<td align='center'><input type='email' value='" + email + "' id='email_"+id+"'></td>" + "<td align='center'><input type='button' value='Update' class='update' data-id='"+id+"' ><input type='button' value='Delete' class='delete' data-id='"+id+"' ></td>"+ "</tr>"; $("#userTable tbody").append(tr_str); } }else{ var tr_str = "<tr class='norecord'>" + "<td align='center' colspan='4'>No record found.</td>" + "</tr>"; $("#userTable tbody").append(tr_str); } } }); } </script> </body> </html>
7. Output
8. Conclusion
Create your methods in the controller to handle the AJAX request and return the response. If you want to send POST request from AJAX request then you need to also pass CSRF_TOKEN in data.
If you found this tutorial helpful then don't forget to share.