3

I am working on a Web Application using Laravel as backend API and AngularJS for frontend. I have successfully fetched the data from Laravel API and displayed it via AngularJS ng-repeat. Now i want a delete button for each record which is displayed in the table. When a user click that delete button it should delete the clicked record.

I did the following try which is working perfectly.But the problem occurs when i click delete button it deletes record from database but it is not refreshing the records list , instead of refreshing it just shows the headers titles of table and nothing else. When i manually refresh it from browser then it displays back the records list. I want to load the list automatically after the record is deleted.

Console Error : Console Error: DELETE http://localhost/ngresulty/public/api/result/50?id=50 500 (Internal Server Error)

Before Delete ( List ):

All records list After delete Scene:

When I press delete , the record is deleted from database but list looks like this

MainCtrl.js

$scope.deleteResult = function(id) {
        $scope.loading = true; 

        Result.destroy(id)
                .success(function(data) {
                    // if successful, we'll need to refresh the comment list
                  Result.get()
                        .success(function(data) {
                            $scope.students = data;
                            $scope.loading = false;
                        });


                });
};

MyAppService.js

angular.module('myAppService', [])

    .factory('Result', function($http) {
        return {
            get : function() {
                return $http.get('api/result');
            },
            show : function(id) {
                return $http.get('api/result/' + id);
            },
            save : function(resultData) {
                return $http({
                    method: 'POST',
                    url: 'api/result',
                    headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
                    data: $.param(resultData)
                });
            },
            destroy : function(id) {
                return $http.delete('api/result/' + id,{params: {id}});
            }
        }

});

App.js

var myApp = angular.module('myApp', ['mainCtrl', 'myAppService']);

Results View :

<table class="table table-striped">
                            <thead>
                              <tr>
                                <th>Roll No</th>
                                <th>Student Name</th>
                                <th>Father Name</th>
                                <th>Obtained Marks</th>
                                <th>Total Marks</th>
                                <th>Percentage</th>
                                <th>Delete</th>
                              </tr>
                            </thead>
                            <tbody ng-hide="loading" ng-repeat="student in students | filter:searchText">
                                  <tr> 
                                    <td>@{{ student.rollno }}</td>
                                    <td>@{{ student.name }}</td>
                                    <td>@{{ student.fname }}</td>
                                    <td>@{{ student.obtainedmarks }}</td>
                                    <td>@{{ student.totalmarks }}</td>
                                    <td>@{{ student.percentage }}</td>
                                    <td>
                                        <a href="#" ng-click="deleteResult(student.id)" class="text-muted btn-danger btn-lg">Delete</a></p>
                                    </td>

                                  </tr>
                             </tbody>
</table>

What I tried but not working :

 $scope.deleteResult = function(id) {
        $scope.loading = true; 

        Result.destroy(id)
            .success(function(data) {

                // do something with data if you want to
                $scope.students.splice(id, 1);

            });
    };

Solution : Whenever you get 500 internal error the issue will be from server side. The issue was with server side all i did was change my destroy service to

 destroy : function(id) {
                return $http.delete('api/result/' + id);
} 

and in laravel controller i was returning a bool value true but i changed that to ID

return \Response::json($studentid);

because i was in need of that ID for success return and then it worked like a charm.

3 Answers 3

1

The problem is Array splice method takes the index of array as first argument and you are providing it Student Id which is not a array index. You have to find the index of student id in the array then pass it into the splice method

$scope.findWithAttr= function(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
    if(array[i][attr] === value) {
        return i;
    }
} }

Now you can call this function is destroy success block.

$scope.deleteResult = function(idToDelete) {
    $scope.loading = true; 

    $http.delete('api/result/' + id,{params: {id}}); }
        .then(function(data) {

            var index=$scope.findWithAttr($scope.students,id,idToDelete);
            $scope.students.splice(index, 1);

        });
};
Sign up to request clarification or add additional context in comments.

7 Comments

same error in console , please read my question . Deletion is working perfectly but the view is not refreshing automatically.
even it is not alerting so it means the destroy success is never called right ? $scope.deleteResult = function(idToDelete) { $scope.loading = true; Result.destroy(idToDelete) .success(function(data) { alert('hello'); }); };
Yes it is not called.
may be you should try .then(function (res) {}) instead of .success
Also if you take a look on delete service destroy : function(id) { return $http.delete('api/result/' + id,{params: {id}}); } is this correct ?
|
0

You are splicing the data incorrectly.

Do like this to splice the data in destroy success block.

var del_index = $scope.students.findIndex(function(d){return d.id == id});
if(del_index>0)//if index of the id to be removed found
  $scope.students.splice(del_index, 1);

5 Comments

still same error DELETE http://localhost/ngresulty/public/api/result/53?id=53 500 (Internal Server Error) @Cyril my new code looks like this now $scope.deleteResult = function(id) { $scope.loading = true; Result.destroy(id) .success(function(data) { var del_index = $scope.students.findIndex(function(d){return d.id == id}); if(del_index>0)//if index of the id to be removed found $scope.students.splice(del_index, 1); };
even it is not alerting so it means the destroy success is never called right ? $scope.deleteResult = function(idToDelete) { $scope.loading = true; Result.destroy(idToDelete) .success(function(data) { alert('hello'); }); };
http://localhost/ngresulty/public/api/result/53?id=53 giving a 500 status means its a server issue. The delete ajax success block will never get called.
Bro, this has nothing to do with angular you have to change the server side code, to fix the 500 error.
Great ! The issue was with server side all i did was change my destroy service to destroy : function(id) { return $http.delete('api/result/' + id); } and in laravel controller i was returning a bool value true but i changed that to ID return \Response::json($studentid); because i was in need of that ID for success return and then it worked like a charm.
0

There is a javascript library called lodash

This library provides the remove function where you can remove an element from the data.

Sometimes slice does not work. SO try this hopefully it would work.

 $scope.deleteResult = function(id) {
    $scope.loading = true; 

    Result.destroy(id)
        .success(function(data) {

            // do something with data if you want to
            _.remove($scope.students,function(student){
             return id==studednt.id; 
             }

        });
};

2 Comments

Aas you are saying, the server is responding you Internal server error after deleting the record. You server response never comes in the success method, if there is any exception thrown by the server. It must come in the .error() method.
yea when my code in controller was return \Response::json('success'=>'true'); then list was not refreshing but when I changed that to return \Response::json($studentid); which is sending Student ID to API then it worked. May be I am wrong but I did that changes and then it worked, before these changes I tried to insert alert('message') in . success but it was not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.