Laravel 5 Ajax CRUD example for web application without page refresh

Laravel 5 Ajax CRUD example for web application without page refresh

Laravel 5 Ajax CRUD example to build web application without page refresh.

In my last tutorial, i had done CRUD application in Laravel MVC without ajax request, now i am going to tell you how to build CRUD web application without page refresh in Laravel using ajax.

Before this, you should familiar about ajax request, ajax is basically used for affecting webpages without reloading them.

Step 1: Install Laravel 5.2

In this step you will have to install fresh laravel project in your system.

composer create-project --prefer-dist laravel/laravel blog
Step 2: Create a Product Table and Model

In this step you will create a product table so for creating table follow the simple step which is mention below.First create migration for products table using Laravel 5 php artisan command,so first run this command -

php artisan make:migration create_products_table

Now you will get a migration file in following path database/migrations and you will have to simply put following code in migration file to create products table.

  1. use Illuminate\Database\Schema\Blueprint;
  2. use Illuminate\Database\Migrations\Migration;
  3. class CreateProductsTable extends Migration
  4. {
  5. public function up()
  6. {
  7. Schema::create('products', function (Blueprint $table) {
  8. $table->increments('id');
  9. $table->string('name');
  10. $table->text('details');
  11. $table->timestamps();
  12. });
  13. }
  14. public function down()
  15. {
  16. Schema::drop("products");
  17. }
  18. }

Now run php artisan migrate command to create a product table.

Product Model

Create a model for product table.


  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class Product extends Model
  4. {
  5. public $fillable = ['name','details'];
  6. }
Step3: Create View

Now Create a directory ajax and within this directory create a view file index.blade.php

resources/views/ajax/index.blade.php
  1. <html>
  2. <head>
  3. <title>Laravel CRUD Application using Ajax without Reloading Page</title>
  4. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
  5. </head>
  6. <body>
  7. <div class="container">
  8. <div class="panel panel-primary">
  9. <div class="panel-heading">Laravel CRUD Application using Ajax without Reloading Page
  10. <button id="btn_add" name="btn_add" class="btn btn-default pull-right">Add New Product</button>
  11. </div>
  12. <div class="panel-body">
  13. <table class="table">
  14. <thead>
  15. <tr>
  16. <th>ID</th>
  17. <th>Name</th>
  18. <th>Details</th>
  19. <th>Actions</th>
  20. </tr>
  21. </thead>
  22. <tbody id="products-list" name="products-list">
  23. @foreach ($products as $product)
  24. <tr id="product{{$product->id}}">
  25. <td>{{$product->id}}</td>
  26. <td>{{$product->name}}</td>
  27. <td>{{$product->details}}</td>
  28. <td>
  29. <button class="btn btn-warning btn-detail open_modal" value="{{$product->id}}">Edit</button>
  30. <button class="btn btn-danger btn-delete delete-product" value="{{$product->id}}">Delete</button>
  31. </td>
  32. </tr>
  33. @endforeach
  34. </tbody>
  35. </table>
  36. </div>
  37. </div>
  38. <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  39. <div class="modal-dialog">
  40. <div class="modal-content">
  41. <div class="modal-header">
  42. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
  43. <h4 class="modal-title" id="myModalLabel">Product</h4>
  44. </div>
  45. <div class="modal-body">
  46. <form id="frmProducts" name="frmProducts" class="form-horizontal" novalidate="">
  47. <div class="form-group error">
  48. <label for="inputName" class="col-sm-3 control-label">Name</label>
  49. <div class="col-sm-9">
  50. <input type="text" class="form-control has-error" id="name" name="name" placeholder="Product Name" value="">
  51. </div>
  52. </div>
  53. <div class="form-group">
  54. <label for="inputDetail" class="col-sm-3 control-label">Details</label>
  55. <div class="col-sm-9">
  56. <input type="text" class="form-control" id="details" name="details" placeholder="details" value="">
  57. </div>
  58. </div>
  59. </form>
  60. </div>
  61. <div class="modal-footer">
  62. <button type="button" class="btn btn-primary" id="btn-save" value="add">Save changes</button>
  63. <input type="hidden" id="product_id" name="product_id" value="0">
  64. </div>
  65. </div>
  66. </div>
  67. </div>
  68. </div>
  69. <meta name="_token" content="{!! csrf_token() !!}" />
  70. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  71. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  72. <script src="{{asset('js/ajaxscript.js')}}"></script>
  73. </body>
  74. </html>
Step4: Include JS file

Now in this step create a ajaxscript.js file in following path public/js/ajaxscript.js

public/js/ajaxscript.js
  1. var url = "http://localhost:8080/blog/public/productajaxCRUD";
  2. //display modal form for product editing
  3. $(document).on('click','.open_modal',function(){
  4. var product_id = $(this).val();
  5. $.get(url + '/' + product_id, function (data) {
  6. //success data
  7. console.log(data);
  8. $('#product_id').val(data.id);
  9. $('#name').val(data.name);
  10. $('#details').val(data.details);
  11. $('#btn-save').val("update");
  12. $('#myModal').modal('show');
  13. })
  14. });
  15. //display modal form for creating new product
  16. $('#btn_add').click(function(){
  17. $('#btn-save').val("add");
  18. $('#frmProducts').trigger("reset");
  19. $('#myModal').modal('show');
  20. });
  21. //delete product and remove it from list
  22. $(document).on('click','.delete-product',function(){
  23. var product_id = $(this).val();
  24. $.ajaxSetup({
  25. headers: {
  26. 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
  27. }
  28. })
  29. $.ajax({
  30. type: "DELETE",
  31. url: url + '/' + product_id,
  32. success: function (data) {
  33. console.log(data);
  34. $("#product" + product_id).remove();
  35. },
  36. error: function (data) {
  37. console.log('Error:', data);
  38. }
  39. });
  40. });
  41. //create new product / update existing product
  42. $("#btn-save").click(function (e) {
  43. $.ajaxSetup({
  44. headers: {
  45. 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
  46. }
  47. })
  48. e.preventDefault();
  49. var formData = {
  50. name: $('#name').val(),
  51. details: $('#details').val(),
  52. }
  53. //used to determine the http verb to use [add=POST], [update=PUT]
  54. var state = $('#btn-save').val();
  55. var type = "POST"; //for creating new resource
  56. var product_id = $('#product_id').val();;
  57. var my_url = url;
  58. if (state == "update"){
  59. type = "PUT"; //for updating existing resource
  60. my_url += '/' + product_id;
  61. }
  62. console.log(formData);
  63. $.ajax({
  64. type: type,
  65. url: my_url,
  66. data: formData,
  67. dataType: 'json',
  68. success: function (data) {
  69. console.log(data);
  70. var product = '<tr id="product' + data.id + '"><td>' + data.id + '</td><td>' + data.name + '</td><td>' + data.details + '</td>';
  71. product += '<td><button class="btn btn-warning btn-detail open_modal" value="' + data.id + '">Edit</button>';
  72. product += ' <button class="btn btn-danger btn-delete delete-product" value="' + data.id + '">Delete</button></td></tr>';
  73. if (state == "add"){ //if user added a new record
  74. $('#products-list').append(product);
  75. }else{ //if user updated an existing record
  76. $("#product" + product_id).replaceWith( product );
  77. }
  78. $('#frmProducts').trigger("reset");
  79. $('#myModal').modal('hide')
  80. },
  81. error: function (data) {
  82. console.log('Error:', data);
  83. }
  84. });
  85. });
Step5: Add Routes

In routes, I define all functionality for handling ajax request such as listing product, read product details, create product, update product and delete product. All the activity will be done by using ajax in Laravel.

  1. use Illuminate\Http\Request;
  2. Route::get('productajaxCRUD', function () {
  3. $products = App\Product::all();
  4. return view('ajax.index')->with('products',$products);
  5. });
  6. Route::get('productajaxCRUD/{product_id?}',function($product_id){
  7. $product = App\Product::find($product_id);
  8. return response()->json($product);
  9. });
  10. Route::post('productajaxCRUD',function(Request $request){   
  11. $product = App\Product::create($request->input());
  12. return response()->json($product);
  13. });
  14. Route::put('productajaxCRUD/{product_id?}',function(Request $request,$product_id){
  15. $product = App\Product::find($product_id);
  16. $product->name = $request->name;
  17. $product->details = $request->details;
  18. $product->save();
  19. return response()->json($product);
  20. });
  21. Route::delete('productajaxCRUD/{product_id?}',function($product_id){
  22. $product = App\Product::destroy($product_id);
  23. return response()->json($product);
  24. });

Click here to see demo of this application how crud work in Laravel with ajax....

Phone: (+91) 8800417876
Noida, 201301