skip to Main Content

I am creating a CRUD Application using Ajax in Laravel 8. And the problem is I want to reload my table using ajax without reloading the whole page but it’s not reloading. I tried a lot of ways but it doesn’t work. How can I do that?
enter image description here

This is my code in books.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Datatables</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css" />
</head>

<body>
<div class="container-fluid">
    <div class="row">
        <h1 class="text-center fw-bold">Bootstrap Datatable</h1>
    </div>
    <div class="row">
        <div class="col-lg-2"></div>
        <div class="col-lg-8">
            <div class="mb-3">
                <!-- Button trigger modal -->
                <button type="button" id="createNewBook" class="btn btn-success" data-bs-toggle="modal"
                    data-bs-target="#addmodel">
                    Add Record
                </button>
            </div>
            <table id="datatables" class="table">
                <thead>
                    <tr>
                        <th scope="col">Book_ID</th>
                        <th scope="col">Book_Name</th>
                        <th scope="col">Auther</th>
                        <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody id="tbody">

                    @foreach ($books as $row)
                    <tr>
                        <th scope="row">{{ $row->id }}</th>
                        <td>{{$row->title }}</td>
                        <td>{{ $row->author }}</td>
                        <td>
                            <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->id . '"
                                data-original-title="Edit" class="edit btn btn-primary btn-sm editBook">Edit</a>
                            <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->id . '"
                                data-original-title="Delete" class="btn btn-danger btn-sm deleteBook">Delete</a>
                        </td>
                    </tr>

                    @endforeach
                </tbody>
            </table>
        </div>
        <div class="col-lg-2"></div>
    </div>
</div>


<!-- Modal -->
<div class="modal fade" id="addmodel" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Add New Book</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="bookForm" name="bookForm" class="form-horizontal">
                    @csrf
                    <input type="hidden" name="book_id" id="book_id">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Title</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="title" name="title"
                                placeholder="Enter Title" value="" maxlength="50" required="">
                        </div>
                    </div>

                    <div class="form-group mt-3">
                        <label class="col-sm-2 control-label">Author</label>
                        <div class="col-sm-12">
                            <textarea id="author" name="author" required="" placeholder="Enter Author"
                                class="form-control"></textarea>
                        </div>
                    </div>

                    <div class="col-sm-offset-2 col-sm-10 mt-3">
                        <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes
                        </button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
            </div>
        </div>
    </div>
</div>



<script src="https://code.jquery.com/jquery-3.6.0.min.js"
    integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous">
</script>
<script type="text/javascript">
$("#datatables").DataTable({});
$("#bookForm").submit(function(e) {
    e.preventDefault();

    var title = $("#title").val();
    var author = $("#author").val();
    var _token = $("input[name=_token]").val();

    $.ajax({
        type: "POST",
        url: "{{route('book.add')}}",
        data: {
            title: title,
            author: author,
            _token: _token
        },
        success: function(response) {
            if (response) {
                $("#bookForm")[0].reset();
                $("#addmodel").modal("hide");
            }
        }
    });
    $("#saveBtn").click(function() {
        $("#tbody").load("#tbody");
    });

});
</script>

And this is my code in Controller

<?PHP

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsBook;

class BookController extends Controller
{
    public function index()
    {
        $books = Book::all();
        return view('books', compact('books'));
    }

    public function insert(Request $request)
    {
        $book = new Book();
        $book->title = $request->title;
        $book->author = $request->author;
        $book->save();
        return response()->json($book);
    }
}

So how can I do that, please help me out…

5

Answers


  1. This question already has an answer by another user but i can repeat it here for you.

    <script>
    $('#tbody').load(document.URL +  ' #tbody');
    </script>
    
    Login or Signup to reply.
  2. Use this for eg.

    window.newSetInterval = window.setInterval; window.setInterval = function(func, interval) { var interval = newSetInterval(func, interval); }

    Login or Signup to reply.
  3. replace your ajax with this

    $.ajax({
        type: "POST",
        url: "{{route('book.add')}}",
        data: {
            title: title,
            author: author,
            _token: _token
        },
        success: function(response) {
            if (response) {
                $("#bookForm")[0].reset();
                $('#tbody').load(document.URL +  ' #tbody');
                $("#addmodel").modal("hide");
            }
        }
    });
    
    Login or Signup to reply.
  4. I hope I’m not too much late but u can do something like below:-

    1. Create a page load.blade.php in views folder

    2. In the Controller code below

    <?PHP
    
    namespace AppHttpControllers;
    
    use IlluminateHttpRequest;
    use AppModelsBook;
    
    class BookController extends Controller
    {
        public function index()
        {
            $books = Book::all();
            return view('books', compact('books'));
        }
    
        public function insert(Request $request)
        {
            $book = new Book();
            $book->title = $request->title;
            $book->author = $request->author;
            $book->save();
            $html=view('load',compact($book))->render();
            return response()->json(['html'=>$html]);
        }
    }
    
    1. In load.blade.php file code below
    @foreach ($book as $row)
    <tr>
       <th scope="row">{{ $row->id }}</th>
       <td>{{$row->title }}</td>
       <td>{{ $row->author }}</td>
       <td>
           <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->id . '"
                                    data-original-title="Edit" class="edit btn btn-primary btn-sm editBook">Edit</a>
          <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->id . '"
                                    data-original-title="Delete" class="btn btn-danger btn-sm deleteBook">Delete</a>
        </td>
    </tr>
    
    @endforeach
    
    1. In the Ajax code below
    $.ajax({
        type: "POST",
        url: "{{route('book.add')}}",
        data: {
            title: title,
            author: author,
            _token: _token
        },
        success: function(response) {
            if (response) {
                $("#bookForm")[0].reset();
                $('#tbody').html(response.html);
                $("#addmodel").modal("hide");
            }
        }
    });
    

    I hope this helps, if any query do ask.😊

    Login or Signup to reply.
  5. Someone already answered with this, with a small problem.

    Here’s a working fix:

    <script>
    $('#tbody').load(document.URL +  ' #tbody tr');
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search