onlinecode

Laravel 5 Ajax CRUD example for web application without page refresh

Laravel 5 Ajax CRUD example for web application without page refresh

In this post we will give you information about Laravel 5 Ajax CRUD example for web application without page refresh. Hear we will give you detail about Laravel 5 Ajax CRUD example for web application without page refreshAnd how to use it also give you demo for it if it is necessary.

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 "5.2.*"

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 IlluminateDatabaseSchemaBlueprint;
  2. use IlluminateDatabaseMigrationsMigration;
  3. class CreateProductsTable extends Migration
  4. {
  5. public functionup()
  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 functiondown()
  15. {
  16. Schema::drop("products");
  17. }
  18. }
use IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;class CreateProductsTable extends Migration{    public function up()    {        Schema::create('products', function (Blueprint $table) {            $table->increments('id');            $table->string('name');            $table->text('details');            $table->timestamps();        });    }    public function down()    {        Schema::drop("products");    }}

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

Product Model

Create a model for product table.

  1. namespace App;
  2. use IlluminateDatabaseEloquentModel;
  3. class Product extends Model
  4. {
  5. public $fillable=['name','details'];
  6. }
namespace App;use IlluminateDatabaseEloquentModel;class Product extends Model{    public $fillable = ['name','details'];}

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. <linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"rel="stylesheet">
  5. </head>
  6. <body>
  7. <divclass="container">
  8. <divclass="panel panel-primary">
  9. <divclass="panel-heading">Laravel CRUD Application using Ajax without Reloading Page
  10. <buttonid="btn_add"name="btn_add"class="btn btn-default pull-right">Add New Product</button>
  11. </div>
  12. <divclass="panel-body">
  13. <tableclass="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. <tbodyid="products-list"name="products-list">
  23. @foreach ($products as $product)
  24. <trid="product{{$product->id}}">
  25. <td>{{$product->id}}</td>
  26. <td>{{$product->name}}</td>
  27. <td>{{$product->details}}</td>
  28. <td>
  29. <buttonclass="btn btn-warning btn-detail open_modal"value="{{$product->id}}">Edit</button>
  30. <buttonclass="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. <divclass="modal fade"id="myModal"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">
  39. <divclass="modal-dialog">
  40. <divclass="modal-content">
  41. <divclass="modal-header">
  42. <buttontype="button"class="close"data-dismiss="modal"aria-label="Close"><spanaria-hidden="true">×</span></button>
  43. <h4class="modal-title"id="myModalLabel">Product</h4>
  44. </div>
  45. <divclass="modal-body">
  46. <formid="frmProducts"name="frmProducts"class="form-horizontal"novalidate="">
  47. <divclass="form-group error">
  48. <labelfor="inputName"class="col-sm-3 control-label">Name</label>
  49. <divclass="col-sm-9">
  50. <inputtype="text"class="form-control has-error"id="name"name="name"placeholder="Product Name"value="">
  51. </div>
  52. </div>
  53. <divclass="form-group">
  54. <labelfor="inputDetail"class="col-sm-3 control-label">Details</label>
  55. <divclass="col-sm-9">
  56. <inputtype="text"class="form-control"id="details"name="details"placeholder="details"value="">
  57. </div>
  58. </div>
  59. </form>
  60. </div>
  61. <divclass="modal-footer">
  62. <buttontype="button"class="btn btn-primary"id="btn-save"value="add">Save changes</button>
  63. <inputtype="hidden"id="product_id"name="product_id"value="0">
  64. </div>
  65. </div>
  66. </div>
  67. </div>
  68. </div>
  69. <metaname="_token"content="{!! csrf_token() !!}"/>
  70. <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  71. <scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  72. <scriptsrc="{{asset('js/ajaxscript.js')}}"></script>
  73. </body>
  74. </html>
<html>  <head>   <title>Laravel CRUD Application using Ajax without Reloading Page</title>      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">   </head><body><div ><div > <div >Laravel CRUD Application using Ajax without Reloading Page <button id="btn_add" name="btn_add" >Add New Product</button>    </div>      <div >        <table >        <thead>          <tr>            <th>ID</th>            <th>Name</th>            <th>Details</th>            <th>Actions</th>          </tr>         </thead>         <tbody id="products-list" name="products-list">           @foreach ($products as $product)            <tr id="product{{$product->id}}">             <td>{{$product->id}}</td>             <td>{{$product->name}}</td>             <td>{{$product->details}}</td>              <td>              <button  value="{{$product->id}}">Edit</button>              <button  value="{{$product->id}}">Delete</button>              </td>            </tr>            @endforeach        </tbody>        </table>       </div>       </div>    <div  id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">        <div >           <div >             <div >             <button type="button"  data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>                <h4  id="myModalLabel">Product</h4>            </div>            <div >            <form id="frmProducts" name="frmProducts"  novalidate="">                <div >                 <label for="inputName" >Name</label>                   <div >                    <input type="text"  id="name" name="name" placeholder="Product Name" value="">                   </div>                   </div>                 <div >                 <label for="inputDetail" >Details</label>                    <div >                    <input type="text"  id="details" name="details" placeholder="details" value="">                    </div>                </div>            </form>            </div>            <div >            <button type="button"  id="btn-save" value="add">Save changes</button>            <input type="hidden" id="product_id" name="product_id" value="0">            </div>        </div>      </div>  </div></div>    <meta name="_token" content="{!! csrf_token() !!}" />    <script src="{{asset('js/jquery.js')}}"></script>    <script src="{{asset('js/bootstrap.js')}}"></script>    <script src="{{asset('js/ajaxscript.js')}}"></script></body></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 value="'+ data.id +'">Edit</button>';
  72. product +=' <button 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. });
    var url = "/productajaxCRUD";    //display modal form for product editing    $(document).on('click','.open_modal',function(){        var product_id = $(this).val();               $.get(url + '/' + product_id, function (data) {            //success data            console.log(data);            $('#product_id').val(data.id);            $('#name').val(data.name);            $('#details').val(data.details);            $('#btn-save').val("update");            $('#myModal').modal('show');        })     });    //display modal form for creating new product    $('#btn_add').click(function(){        $('#btn-save').val("add");        $('#frmProducts').trigger("reset");        $('#myModal').modal('show');    });    //delete product and remove it from list    $(document).on('click','.delete-product',function(){        var product_id = $(this).val();         $.ajaxSetup({            headers: {                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')            }        })        $.ajax({            type: "DELETE",            url: url + '/' + product_id,            success: function (data) {                console.log(data);                $("#product" + product_id).remove();            },            error: function (data) {                console.log('Error:', data);            }        });    });    //create new product / update existing product    $("#btn-save").click(function (e) {        $.ajaxSetup({            headers: {                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')            }        })        e.preventDefault();         var formData = {            name: $('#name').val(),            details: $('#details').val(),        }        //used to determine the http verb to use [add=POST], [update=PUT]        var state = $('#btn-save').val();        var type = "POST"; //for creating new resource        var product_id = $('#product_id').val();;        var my_url = url;        if (state == "update"){            type = "PUT"; //for updating existing resource            my_url += '/' + product_id;        }        console.log(formData);        $.ajax({            type: type,            url: my_url,            data: formData,            dataType: 'json',            success: function (data) {                console.log(data);                var product = '<tr id="product' + data.id + '"><td>' + data.id + '</td><td>' + data.name + '</td><td>' + data.details + '</td>';                product += '<td><button  value="' + data.id + '">Edit</button>';                product += ' <button  value="' + data.id + '">Delete</button></td></tr>';                if (state == "add"){ //if user added a new record                    $('#products-list').append(product);                }else{ //if user updated an existing record                    $("#product" + product_id).replaceWith( product );                }                $('#frmProducts').trigger("reset");                $('#myModal').modal('hide')            },            error: function (data) {                console.log('Error:', data);            }        });    });

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

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

Show Demo

Label :

PHP

Object Oriented Programming

Laravel PHP Framework

jQuery

How To

JavaScript

Hope this code and post will helped you for implement Laravel 5 Ajax CRUD example for web application without page refresh. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Exit mobile version