skip to Main Content

I have a Laravel 5.8 project where I want to use Ajax for my CRUD and I use datatables of course. It is working fine, I successfully saved my data in database but there are two problems. Let me show you the code first.

This is my Controller:

<?php

namespace AppHttpControllersAdmin;

use IlluminateHttpRequest;
use AppHttpControllersController;
use AppRestaurant;
use AppKitchen;
use Validator;

class RestaurantsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        if(request()->ajax())
        {
            return datatables()->of(Restaurant::latest()->get())
                    ->addColumn('action', function($data){
                        $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
                        $button .= '&nbsp;&nbsp;';
                        $button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
                        return $button;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
        return view('admin.restaurants.index');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        $rules = array(
            'naziv' => 'required|unique:restaurants|max:90',
            'adresa' => 'required|max:150',
            /*
            'pon_pet' => 'required',
            'min_dostava' => 'required|numeric|max:5',
            'vrijeme_dostave' => 'required|max:10|numeric',
            'cijena_dostave' => 'required|numeric|max:5',
            'podrucije_grada' => 'required',
            'br_telefona' => 'required|numeric|unique:restaurants',
            'lokacija' => 'max:999',
            'kuhinja_id' => 'required',
            'user_id' => 'required'
            */
        );

        $error = Validator::make($request->all(), $rules);

        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $form_data = array(
            'naziv' => $request->naziv,
            'adresa' => $request->adresa,
            /*
            'pon_pet' => $request->pon_pet,
            'min_dostava' => $request->min_dostava,
            'vrijeme_dostave' => $request-> vrijeme_dostave,
            'cijena_dostave' => $request->cijena_dostave,
            'podrucije_grada' => $request->podrucije_grada,
            'br_telefona' => $request->br_telefona,
            'lokacija' => $request->lokacija,
            'kuhinja_id' => $request->kuhinja_id,
            'user_id' => $request->user_id
            */
        );

        Restaurant::create($form_data);

        return response()->json(['success' => 'Data Added successfully.']);
    }
}

And in my blade:

!-- DataTales Example -->
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold">Baza restorana</h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Naziv</th>
                        <th>Adresa</th>
                        <th>Action</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
    aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <span id="form_result"></span>
                <form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
                    @csrf
                    <div class="form-group">
                        <label class="control-label col-md-4">Naziv</label>
                        <div class="col-md-8">
                            <input type="text" name="naziv" id="naziv" class="form-control" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-4">Adresa</label>
                        <div class="col-md-8">
                            <input type="text" name="adresa" id="adresa" class="form-control" />
                        </div>
                    </div>
                    <br />
                    <div class="form-group" align="center">
                        <input type="hidden" name="action" id="action" />
                        <input type="hidden" name="hidden_id" id="hidden_id" />
                        <input type="submit" name="action_button" id="action_button" class="btn btn-warning"
                            value="Add" />
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

@endsection

<script>
    $(document).ready(function(){

 $('#dataTable').DataTable({
  processing: true,
  serverSide: true,
  ajax:{
   url: "{{ route('admin.restaurants.index') }}",
  },
  columns:[
   {
    data: 'id',
    name: 'id'
   },
   {
    data: 'naziv',
    name: 'naziv'
   },
   {
    data: 'adresa',
    name: 'adresa'
   },
   {
    data: 'action',
    name: 'action',
    orderable: false
   }
  ]
 });

 $('#create_record').click(function(){
  $('.modal-title').text("Add New Record");
     $('#action_button').val("Add");
     $('#action').val("Add");
     $('#formModal').modal('show');
 });

 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  if($('#action').val() == 'Add')
  {
   $.ajax({
    url:"{{ route('admin.restaurants.store') }}",
    method:"POST",
    data: new FormData(this),
    contentType: false,
    cache:false,
    processData: false,
    dataType:"json",
    success:function(data)
    {
     var html = '';
     if(data.errors)
     {
      html = '<div class="alert alert-danger">';
      for(var count = 0; count < data.errors.length; count++)
      {
       html += '<p>' + data.errors[count] + '</p>';
      }
      html += '</div>';
     }
     if(data.success)
     {
      html = '<div class="alert alert-success">' + data.success + '</div>';
      $('#sample_form')[0].reset();
      $('#dataTable').DataTable().ajax.reload();
     }
     $('#form_result').html(html);
    }
   })
  }
 });
});
</script>

ISSUES

The first issue is that when I click on Add to submit my inputs it saves my data but it’s showing only response on white page and not just add it in datatable.

And the second issue is that my data is not even showing in datatable. It’ empty and I don’t know why.

Please help, what should I do? Any suggestions?

2

Answers


  1. Did you add admin.restaurants.index in your web.php ?

    Login or Signup to reply.
  2. I think both of your issues come from the same problem, you reassign the datatable so it becomes empty (because you’re not assign it with the previous config just $('#dataTable').DataTable()) Try this, first add your datatable to variable:

    let datatable = $('#dataTable').DataTable({
    ...
    

    So you can refresh the same datatable without reassigning it with

    datatable.ajax.reload()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search