How To Insert Check Box Value Using Ajax In Laravel

admin_img Posted By Bajarangi soft , Posted On 20-01-2021

Using Ajax is another way to Store a checkbox value with json in laravel.

How To Insert Check Box Value Using Ajax In Laravel

Step 1:Create a table and model for Inserting checkbox value.
 

class Blog extends Model
{
    public $table = 'product';

    protected $fillable = [
        'product_name', 'product_title','vehicle'
    ];
}


Step 2: Create a View file like blog.blade.php and modal for inserting checkbox value and make ajax code for inserting data.
resources/views/welcome.blade.php

 

<html>
  <head>
   <title>Laravel </title>  
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> 
  </head>
<body><br>
<div id="alert" class="alert-success new-window" data-message="my message">
        </div>
<div class="container">
<div class="panel panel-primary">
 <div class="panel-heading">Products
 <button id="btn_add" name="btn_add" class="btn btn-default pull-right">Add New Product</button>
    </div>
      <div class="panel-body"> 
       <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Product Name</th>
            <th>Product Title</th>
            <th>Actions</th>
          </tr>   
         </thead>
         <tbody id="products-list" name="products-list">
           @foreach ($product as $product)
            <tr id="product">
             <td>{{$product->id}}</td>
             <td>{{$product->product_name}}</td>
             <td>{{$product->product_title}}</td>
              <td>
              <button class="btn btn-warning btn-detail open_modal btn-edit" value="{{$product->id}}">Edit</button>
              <button class="btn btn-danger btn-delete delete-product" value="{{$product->id}}">Delete</button>
              </td>
            </tr>
             @endforeach
        </tbody>
        </table>
       </div>
       </div>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">Product</h4>
              </div>
              <div class="modal-body">
                <form id="frmProducts" name="frmProducts" class="form-horizontal" novalidate="">

                  <div class="form-group error">
                    <label for="inputName" class="col-sm-3 control-label">Product Name</label>
                    <div class="col-sm-9">
                      <input type="text" class="form-control has-error" id="product_name" name="product_name" placeholder="Product Name" value="">
                    </div>
                  </div>

                  <div class="form-group">
                    <label for="inputDetail" class="col-sm-3 control-label">Product Title</label>
                    <div class="col-sm-9">
                     <input type="text" class="form-control" id="product_title" name="product_title" placeholder="Product Title" value="">
                    </div>
                  </div>

                  <div class="form-group">
                    <label for="inputDetail" class="col-sm-3 control-label">Vehicle:</label>
                    <div class="col-sm-9">
                     <input type="checkbox" class="get_value" id="vehicle1" name="vehicle[]" value="1">
                      <label for="vehicle1"> I have a bike</label><br>
                      <input type="checkbox" class="get_value" id="vehicle2" name="vehicle[]" value="2">
                      <label for="vehicle2"> I have a car</label><br>
                      <input type="checkbox" class="get_value" id="vehicle3" name="vehicle[]" value="3">
                      <label for="vehicle3"> I have a boat</label><br><br>
                    </div>
                  </div>          
                </form>
              </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary" id="btn-save" value="add">Save</button>
              <input type="hidden" id="product_id" name="product_id" value="0">
            </div>
          </div>
        </div>
      </div>
    <meta name="_token" content="{!! csrf_token() !!}" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="{{asset('js/ajaxscript.js')}}"></script>
    <script type="text/javascript">
    $(document).ready(function(){

      $('#btn_add').click(function(){
        $('#myModal').modal('show');
      });

      $('#btn-save').on('click',function(event){
        var product_name = $("#product_name").val();
        var product_title = $("#product_title").val();
        // var vehicle = $("#vehicle").val();
        var vehicle = [];  
           $('.get_value').each(function(){  
                if($(this).is(":checked"))  
                {  
                  vehicle.push($(this).val());  
                }  
           });  
           vehicles = vehicle.toString();
          event.preventDefault();
          $.ajax({
            url:"{{ url('store') }}",
            type:"POST",
            data:{"_token": "{{ csrf_token() }}",product_name:product_name,product_title,product_title,vehicles:vehicles} ,
            dataType:"json",
            success:function(data)
            {
                $('#myModal').modal('hide');  
                $('#alert').text('Data Inserted Successfully..');

                setTimeout(function() {
                $('#alert').fadeOut('slow');
                    }, 10000);
                window.location.href= "blog";
            },    
            error: function(data){
                 alert("Error")
            }
          });
      });
    });
  </script>
</body>
</html>


Step: 3 Create a function in controller for insert data of checkbox from the model and send response using json to ajax .
app/Http/Controllers/BlogController.php

 

public function insert(Request $request)
    {
        $rules = array(
            'product_name'    =>  'required',
            'product_title'     =>  'required',
            'vehicle'     =>  'required',
           
        );
        $data = array(
            'product_name'        =>  $request->product_name,
            'product_title'         =>  $request->product_title,      
            'vehicle'         =>  $request->vehicles      
        );
        $value = Blog::create($data);           
        return response()->json(200);
    }


Step: 4 Make a route for connection with controller.
app/Http/routes.php

 

Route::post('store', 'BlogController@insert');

Related Post