Insert update delete Using Laravel 5.2 Ajax CRUD laravel without refresh page

Insert update delete Using Laravel 5.2 Ajax CRUD laravel without refresh page

CRUD operations using jQuery and Ajax in Laravel 5.2 Example

Step 1: Install Laravel 5.2 using Xampp

composer create-project --prefer-dist laravel/laravel blog "5.2.*"

Step 2: Create a MyItem Table and Model using Laravel

php artisan make:migration create_MyItems_table

get a migration file

database/migrations

migration file to create MyItems table using Laravel

    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    class CreateMyItemsTable extends Migration
    {
        public function up()
        {
            Schema::create('MyItems', function (Blueprint $livetabledata) {
                $livetabledata->increments('id');
                $livetabledata->string('name');
                $livetabledata->text('comment');
                $livetabledata->timestamps();
            });
        }
        public function down()
        {
            Schema::drop("MyItems");
        }
    }

Now run simple php artisan migrate cmd to run command to create a MyItem table.

MyItem Model

Create a model for MyItem table.

    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class MyItem extends Model
    {
        public $fillable = ['name','comment'];
    }

Step3: Create View using Laravel

Now Create a all this file directory ajax file and within this same directory create a view file like as a index.blade.php

resources/views/ajax/index.blade.php

    
      
       Laravel Create,Read,Update and Delete statement Application using Ajax without Reloading Page  
         
      
    
    
Laravel Create,Read,Update and Delete statement Application using Ajax without Reloading Page
@foreach ($MyItems as $MyItem) id}}"> @endforeach
ID Name comment Actions
{{$MyItem->id}} {{$MyItem->name}} {{$MyItem->comment}}

Step4: Include JS file using Laravel Project

Now in this simple step create a file like as a ajaxscript.js file in following this dir path public/js/ajaxscript.js

public/js/ajaxscript.js

    var url = "http://localhost:8080/blog/public/crud";
    //display modal form for MyItem editing
    $(document).on('click','.open_modal',function(){
        var MyItem_id = $(this).val();
       
        $.get(url + '/' + MyItem_id, function (data) {
            //success data
            console.log(data);
            $('#MyItem_id').val(data.id);
            $('#name').val(data.name);
            $('#comment').val(data.comment);
            $('#laracrud-btnsave').val("update");
            $('#laravelmodel').modal('show');
        }) 
    });
    //display modal form for creating new MyItem
    $('#laravel-addrecord').click(function(){
        $('#laracrud-btnsave').val("add");
        $('#laraliveForm').trigger("reset");
        $('#laravelmodel').modal('show');
    });
    //delete MyItem and remove it from list
    $(document).on('click','.delete-MyItem',function(){
        var MyItem_id = $(this).val();
         $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })
        $.ajax({
            type: "DELETE",
            url: url + '/' + MyItem_id,
            success: function (data) {
                console.log(data);
                $("#MyItem" + MyItem_id).remove();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
    
    $("#laracrud-btnsave").click(function (e) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })
        e.preventDefault(); 
        var myformdata = {
            name: $('#name').val(),
            comment: $('#comment').val(),
        }
       
        var state = $('#laracrud-btnsave').val();
        var type = "POST";
        var MyItem_id = $('#MyItem_id').val();;
        var my_url = url;
        if (state == "update"){
            type = "PUT"; 
            my_url += '/' + MyItem_id;
        }
        console.log(myformdata);
        $.ajax({
            type: type,
            url: my_url,
            data: myformdata,
            dataType: 'json',
            success: function (data) {
                console.log(data);
                var MyItem = '' + data.id + '' + data.name + '' + data.comment + '';
                MyItem += '';
                MyItem += ' ';
                if (state == "add"){ 
                    $('#MyItems-list').append(MyItem);
                }else{ 
                    $("#MyItem" + MyItem_id).replaceWith( MyItem );
                }
                $('#laraliveForm').trigger("reset");
                $('#laravelmodel').modal('hide')
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

Step5: Add Routes

In routes using laravel, I define all simple functionality for handling jquery ajax call request such as view MyItem, simple read MyItem comment, create new MyItem, update each MyItem and delete MyItem. All the crud oeration activity will be done by using jquery ajax in Laravel.

    use Illuminate\Http\Request;
    Route::get('MyItemajaxcrud', function () {
        $MyItems = App\MyItem::all();
        return view('ajax.index')->with('MyItems',$MyItems);
    });
    Route::get('MyItemajaxcrud/{MyItem_id?}',function($MyItem_id){
        $MyItem = App\MyItem::find($MyItem_id);
        return response()->json($MyItem);
    });
    Route::post('MyItemajaxcrud',function(Request $request){   
        $MyItem = App\MyItem::create($request->input());
        return response()->json($MyItem);
    });
    Route::put('MyItemajaxcrud/{MyItem_id?}',function(Request $request,$MyItem_id){
        $MyItem = App\MyItem::find($MyItem_id);
        $MyItem->name = $request->name;
        $MyItem->comment = $request->comment;
        $MyItem->save();
        return response()->json($MyItem);
    });
    Route::delete('MyItemajaxcrud/{MyItem_id?}',function($MyItem_id){
        $MyItem = App\MyItem::destroy($MyItem_id);
        return response()->json($MyItem);
    });

Example

Leave a Comment