Home > database >  Page reloading on second click on another anchor using Ajax in Laravel
Page reloading on second click on another anchor using Ajax in Laravel

Time:04-09

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 >
        @if ($departments->isEmpty())
            <div >
                <h1>
                    هیچ ریاست موجود نیست
                </h1>
            </div>
        @else
            <div >
                <h3 >لیست ریاست ها</h3>
            </div><!-- /.box-header -->
            <div >
                <table >
                    <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 }}" >
                                        <span ></span>
                                    </a>
                                    <a href="{{ $department->id }}" >
                                        <span ></span>
                                    </a>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div><!-- /.box-body -->
        @endif
    </div>

here is my Ajax code

<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   '" >'  
                    '<span ></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);
    }
}

CodePudding user response:

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()

  • Related