Issue
Unable to enter success() function instead getting an syntax error of 'Unexpected token R in JSON at position 0 at JSON.parse ()'. But all the background database operations are going as they should.
Note: I am not returning any JSON data from the AJAX call
<html ng-app="PlaylistApp">
<head>
<meta charset="utf-8">
<title>Angular.js Example</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="lib/angular.min.js"></script>
<script>
var playlistApp = angular.module('PlaylistApp', []);
playlistApp.controller('PlaylistCtrl', function ($scope, $http)
{
$http({
method : 'GET',
url : 'http://localhost:8080/SignageSoC/api/playlist/all'
}).then(function success(response) {
$scope.playlists = response.data;
});
$scope.removePlaylist = function(index, playlistId)
{
var i = index;
alert(i);
alert(playlistId);
$http({
method : 'DELETE',
url : 'http://localhost:8080/SignageSoC/api/playlist/'+ playlistId
}).then(function success() {
alert(i);
$scope.playlists.splice(i, 1);
});
}
});
</script>
</head>
<body ng-controller="PlaylistCtrl">
<div>
<br>
<br>
<br>
<table class="center">
<tr>
<th>PlaylistId</th>
<th>Name</th>
<th>Total_duration</th>
<th>Play_continuous</th>
<th>Start_time</th>
<th>End_time</th>
<th>Update</th>
<th>Remove</th>
</tr>
<tr data-ng-repeat="(index,x) in playlists">
<td>{{x.playlistId}}</td>
<td>{{x.name}}</td>
<td>{{x.total_duration}}</td>
<td>{{x.play_continuous}}</td>
<td>{{x.start_time}}</td>
<td>{{x.end_time}}</td>
<td><button data-ng-click="updatePlaylist(index)">Update</button></td>
<td><button data-ng-click="removePlaylist(index, x.playlistId)">Delete</button></td>
</tr>
</table>
</div>
</body>
</html>
Solution
It turns out there is way how we can avoid this exception. Any response from a angular ajax call expects a promise(which will be resolved into an object internally), and JSON.parse will be automatically invoked on that response object.
If we are not returning any JSON object(which in my case is true) then angular throws an Unexpected token (any alphabet) in JSON at position 0 at JSON.parse () exception.
To make ajax call receive any data other than an object, we have to use an inbuilt configuration known as transformResponse attribute and make the parser know that we are not using any JSON data.
To do that I used the following way
$http({
method : 'DELETE',
url : 'http://localhost:8080/SignageSoC/api/playlist/'+ playlistId,
transformResponse: function(response)
{
//alert("Success() starts here");
//alert(response);
return response;
}
}).then(function success(modResponse) {
alert(JSON.stringify(modResponse));
alert(JSON.stringify(modResponse.data));
//$scope.playlists.splice(index, 1);
});
Now, if you print the modified response you can see the data property altered to whatever we are returning.
Then we can perform any opertion that we need on that data.
Answered By - Sarath Raja
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.