Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Page reloading on second click on another anchor using Ajax in Laravel

I make Ajax call for deleting a single record, it works for the first time and refreshes the table content correctly but when I want to delete another record, it reloads the entire page(preventDefault() not working), I don’t know why.
can anyone help me

my HTML code

<div class="box">
        @if ($departments->isEmpty())
            <div class="box-header">
                <h1>
                    هیچ ریاست موجود نیست
                </h1>
            </div>
        @else
            <div class="box-header">
                <h3 class="box-title">لیست ریاست ها</h3>
            </div><!-- /.box-header -->
            <div class="box-body no-padding">
                <table class="table table-condensed">
                    <thead>
                        <tr>
                            <th>شماره</th>
                            <th>ریاست به دری</th>
                            <th>ریاست به پشتو</th>
                            <th>ریاست به انگلیسی</th>
                            <th>تغیرات</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($departments as $department)
                            <tr>
                                <td>{{ $department->id }}</td>
                                <td>{{ $department->nameInDari }}</td>
                                <td>{{ $department->nameInPashto }}</td>
                                <td>{{ $department->nameInEnglish }}</td>
                                <td><a href="{{ $department->id }}" class="edit">
                                        <span class="fa fa-edit"></span>
                                    </a>
                                    <a href="{{ $department->id }}" class="delete text-danger">
                                        <span class="fa fa-remove"></span>
                                    </a>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div><!-- /.box-body -->
        @endif
    </div>

here is my Ajax code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
            }
        });

        $('.delete').click(function(e) {
            e.preventDefault();
            id = $(this).attr('href');
            url = '{{ route('departments.destroy', ':id') }}';
            url = url.replace(':id', id);
            $.ajax({
                type: 'DELETE',
                url: url,
                data: {
                    id: id
                },
                cache: false,
                success: function(data) {
                    if ($.isEmptyObject(data.error)) {
                        reloadContent(data.success);
                    } else {
                        alert(data.error);
                    }
                }
            });
        });
function reloadContent(data) {
            $('tbody').html('');
            var row = '';
            $.each(data, function(key, value) {
                row = '<tr>' +
                    '<td>' + value.id + '</td>' +
                    '<td>' + value.nameInDari + '</td>' +
                    '<td>' + value.nameInPashto + '</td>' +
                    '<td>' + value.nameInEnglish + '</td>' +
                    '<td><a href ="' + value.id + '" class ="edit">' +
                    '<span class ="fa fa-edit"></span></a> ' +
                    '<a href ="' + value.id + '" class="delete text-danger">' +
                    '<span class="fa fa-remove"></span></a>' +
                    '</td>' +
                    '</tr>';
                $('tbody').append(row);
            });
        }
</script>

here is my Laravel code

public function destroy($id)
{
    $department = Departments::find($id);
    if ($department) {
        Departments::destroy($id);
        return response()->json(['success' => Departments::all()], Response::HTTP_OK);
    } else {
        return response()->json(['error' => 'No Record Found with ID = ' . $id], Response::HTTP_OK);
    }
}

>Solution :

please change $('.delete').click(function(e) to $(document).on('click', '.delete', function(e)

$(document).on('click', '.delete', function(e) {

        e.preventDefault();
        id = $(this).attr('href');
        url = '{{ route('departments.destroy', ':id') }}';
        url = url.replace(':id', id);
        $.ajax({
            type: 'DELETE',
            url: url,
            data: {
                id: id
            },
            cache: false,
            success: function(data) {
                if ($.isEmptyObject(data.error)) {
                    reloadContent(data.success);
                } else {
                    alert(data.error);
                }
            }
        });
    });

justify:

at first delete the reloadContent(data) fire and added a new .delete
elements so the method in its old form will not fire on the new elements & use the default dehaviour of <a>

these edits change the method from bind to live for more info please check the following article difference between on() and live() or bind()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading