Home > Software design >  Laravel 8 & Ajax - Insert data into table always refresh loading
Laravel 8 & Ajax - Insert data into table always refresh loading

Time:12-02

First of all, I have to say that I'm beginner with using Ajax, I want to insert the data into db without refreshing the page, every time i submit new kategori, laravel always show message "Data berhasil disimpan", and not redirect to index

Here my controller

public function store(Request $request)
    {
        $kategori = new Kategori();
        $kategori->nama_kategori = $request->nama_kategori;
        $kategori->save();

        return response()->json('Data berhasil disimpan', 200);
    }

Here my modal:

<div class="modal fade" id="modal-form" tabindex="-1" aria-labelledby="modal-form" aria-hidden="true">
    <div class="modal-dialog">
        <form action="" method="post" class="form-horizontal">
            @csrf
            @method('post')

            <div class="modal-content">

                <div class="modal-header">
                    <h5 class="modal-title" id="modal-form">Tambah Kategori</h5>
                </div>

                <div class="modal-body">

                    <div class="form-group">
                        <label for="NamaKategori">Nama Kategori</label>
                        <input type="text" name="nama_kategori" class="form-control" id="NamaKategori"
                            placeholder="Masukan Nama Kategori" required autofocus>
                        <span class="help-block with-errors"></span>
                    </div>

                </div>

                <div class="modal-footer">
                    <button class="btn btn-sm btn-flat btn-primary"><i class="fa fa-save"></i>
                        Simpan</button>
                    <button type="button" class="btn btn-sm btn-flat btn-warning" data-dismiss="modal"><i
                            class="fa fa-arrow-circle-left"></i> Batal</button>
                </div>

            </div>

        </form>
    </div>
</div>

Here my ajax script:

<script>
    let table;

    $(function () {
        table = $('.table').DataTable({
            responsive: true,
            processing: true,
            serverSide: true,
            autoWidth: false,
            ajax: {
                  url: '{{ route('kategori.data') }}',
            },

            columns: [
                {data: 'DT_RowIndex', searchable: false, sortable: false},
                {data: 'nama_kategori'},
                {data: 'aksi', searchable: false, sortable: false},
            ]
        });

        $('#modal-form').validator().on('submit', function (e) {
            if (! e.preventDefault()) {
                $.ajax({
                    url:$('#modal-form form').attr('action'),
                    type: 'post',
                    data: $('#modal-form form').serialize()
                })
                
                .done((respone)=>{
                    $('#modal-form').modal('hide');
                    table.ajax.reload();
                })
                .fail((errors)=>{
                alert('Tidak dapat menyimpan data');
                return;
                });

            }
        });
    });

    function addForm(url) {
        $('#modal-form').modal('show');
        $('#modal-form .modal-title').text('Tambah Kategori');

        $('#modal-form form')[0].reset();
        $('#modal-form form').attr('action', url);
        $('#modal-form [name=_method]').val('post');
        $('#modal-form [name=nama_kategori]').focus();
    }
</script>

When I submit the form, it returns me JSON response like this "Data berhasil disimpan"

CodePudding user response:

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. You can see detail here: Jquery submit()

In your js code $('#modal-form') is not a <form> its just a <div>.

So you should assign an id to the form, and change your code like this:

Modal:

<form id="myForm" action="" method="post" class="form-horizontal">
 ...
</form>

Javascript:

$('#myForm').validator().on('submit', function (e) {
      if (!e.preventDefault()) {
           $.ajax({
               url: $('#myForm').attr('action'),
               type: 'post',
               data: {data : $('#myForm').serialize()}
           })
               .done((respone) => {
                   // your code here
               })
               .fail((errors) => {
                   // your code here
               });
      }
 });
  • Related