I am getting all the data from database as array- so In view my code is-
<tr role="row" ng-repeat="result in searchResults">
<td class="sorting_1"><input type="checkbox"
ng-model="result.status" ng-change="saveCheckboxValue(result.status)"/></td>
</tr>
On clicking checkbox i want to update the value, my js :-
$scope.saveCheckboxValue = function(data){
$scope.result.status= (data == true ? 1 : 0);
alert($scope.result.status);
var successCallback = function(){
$.growl.notice({ message: "Updated successfully!" });
$location.path("/Attendance");
//$scope.get();
$scope.displayError = false;
};
var errorCallback = function() {
$scope.displayError=true;
};
$scope.result.$update(successCallback, errorCallback);
}
I am getting error :
PUT localhost...... 405 Method Not Allowed
Help with solution or idea , How can i do it?
Related
I have some values inside a td in textboxes.what i want to do is when i changed(ng-blur) text box value it should affect other values at the same time and changed values should send to the controller for db operations. how can i do this?
HTML
<td><input type="text" id="outUser" name="outUser" ng-model="dailyAttendance.outUser" ng-init="dailyAttendance.outUser | formatTime" ng-blur="dailyAttendances.sendData(dailyAttendance.outUser)"></td>
<td>{{ dailyAttendance.lateUser | formatTime}}</td>
<td>{{ dailyAttendance.workedUser | formatTime}}</td>
<td>{{ dailyAttendance.OTUser | formatTime}}</td>
angular js
sendData(){
this.success = false;
this.submitted = true;
if(this.$scope.DailyAttendanceForm.$valid) {
this.errors = {};
var that = this;
this.spinnerBar.show(); // hide spinner bar
this.$http.post(this.urls.BASE + '/outTime', this.entity)
.success(
function (response) {
that.success = true;
that.message = response.data;
that.spinnerBar.hide(); // hide spinner bar
})
.error(
function (status) {
that.spinnerBar.hide(); // hide spinner bar
var i=0;
});
}
else{
this.success = false;
}
}
as a exmaple when i changed the 'outUser' value it needs to show same value on lateUser and workedUser fields
After sending your request to the DB and receving a response you should attach the attributs (lateUser,workedUser, .. ) in your controller and assign new values
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<table>
<tr>
<td><input type="text" id="outUser" name="outUser" ng-model="outUser" ng-blur="sendData()"></td>
<td>{{lateUser}}</td>
<td>{{workedUser}}</td>
<td>{{OTUser}}</td>
</tr>
</table>
</div>
angular.module("myApp",[]).controller("MyCtrl", function($scope) {
$scope.sendData = function(){
/**
do same job
**/
/**
attach attributes to the current scope and assign new values
**/
$scope.lateUser = $scope.outUser + "lateUser"
$scope.workedUser = $scope.outUser + "workedUser"
$scope.OTUser = $scope.outUser + "OTUser"
}
});
Full exemple
I am trying to delete this entire row whenever you click the Delete button. This is my jQuery command:
UPDATE: I have updated the click function to my finalized version:
$(document).on('click', '.delete-assignment',function () {
console.log("click");
var data = {
assignment_id: $(this).closest('tr').find('.assignment-id').html(),
class_id: $('#classId').val()
}
var row = $(this).closest('tr');
deleteAssignment(data, function(returnData){
var returnData = JSON.parse(returnData);
if(returnData.status == "Success"){
console.log("yes");
row.hide();
}
});
});
When I click delete, it triggers the deleteAssignment function successfully and returns a callback of {"status":"Success"}. Yet when I returnData.status == "Success" is not being triggered.If I try jQuery.type(returnData), It says string. So I implemented JSON.parse and it says unexpected token in json at position 0
here is my html:
<tbody id="Homework">
<tr>
<td>Homework Test Title</td>
<td>02/16/2017 - 10:00 AM</td>
<td class="assignment-id">51</td>
<td><button type="button" class="btn btn-danger delete-assignment">Delete</button></td>
</tr>
</tbody>
I wanted to also include how I am passing data back to deleteAssignment as a callback (defined in the javascript function (deleteAssignment)
assignment = Assignments.objects.get(id=data['assignment_id'])
assignment.delete()
data = {}
data['status'] = "Success"
return HttpResponse(json.dumps(data), content_type="application/json")
You have a clouser problem.
The variable this inside your callback function is not the same this that inside the click function.
There are several ways to solve this, here is one of them:
$('.delete-assignment').on('click', function () {
var data = {
assignment_id: $(this).closest('tr').find('.assignment-id').html(),
class_id: $('#classId').val()
}
var that = this;
deleteAssignment(data, function(returnData){
console.log(returnData);
if(returnData.status == "Success"){
print("yes");
$(that).closest('tr').remove();
}
});
});
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 ):
After delete Scene:
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>
Delete</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.
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);
});
};
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);
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;
}
});
};
I have a api call who give me the list of data, and I am iterating data via ng-repeat (its a list of more than 100 items)
For getting list of data I have call an Api in App Controller in angularjs like this:
var path = serverUrl + 'api/getAllMails';
$http.get(path).then(function (result) {
$scope.mails=result
})
For Iterating the mails in Html file i have use table like the below
<table>
<tr class="header">
<th class="center">Id</th>
<th class="center">Mode of Payment</th>
<th class="center">Payment Collected</th>
<th class="center">Status</th>
</tr>
<tr ng-repeat="mail in mails">
<td>{{mail.id}}</td>
<td>{{mail.paymentType}}</td>
<td>Rs. {{mail.cost}}
<input type="text" ng-model="mail.cost">
<button ng-click="updateCost=(mail.id, mail.cost)">Update Cost</button>
</td>
<td>{{mail.status}}
<input type="text" ng-model="mail.status">
<button ng-click="updateStatus(mail.id, mail.status)">Update Status</button>
</td>
</tr>
</table>
Suppose in the first iterations the cost will be "100" and the status will be "pending". And I have to update this row only, change cost to "1000" and status will be "Delivered".
In my App controller of Angularjs I have create methods. These two methods are calling apis and updating data in database and return the list of updated mails.
$scope.updateStatus = function(mailId, mailStatus) {
var path = serverUrl + 'api/updateStatus';
$http.get(path, {
params: {
mailId: mailId,
mailStatus: mailStatus
}
}).then(function(result) {
$scope.mails = result
})
}
$scope.updateCost = function(mailId, mailCost) {
var path = serverUrl + 'api/updateStatus';
$http.get(path, {
params: {
mailId: mailId,
mailCost: mailCost
}
}).then(function(result) {
$scope.mails = result
})
}
These code are working fine but while it took lot of time to load a page. So what can I do to reduce the loading time or is there any better way to do the same thing.
Any help will be appreciable. Thank you
You are replacing the entire dataset when there is no reason for that, you should only update the row you change. Ensure your updateStatus return the object you update and update that item in $scope.mails
In example
$scope.updateCost = function(mailId, mailCost) {
var path = serverUrl + 'api/updateStatus';
$http.get(path, {
params: {
mailId: mailId,
mailStatus: mailCost
}
}).then(function(result) {
// result is the item you changed
for (var i = $scope.mails.length - 1; i >= 0; i--) {
if($scope.mails[i].id === mailId) {
$scope.mails[i] = result;
return;
}
};
})
}
I am in the process of learning about knockout/json/mvc et al and have tried to put together an example project, but for some reason I am unable to get the data to bind correctly.
In the code snippet below, I get some JSON data from a web server and then try to map it to a function and then eventually to my knockout observableArray. What I then do is use this observableArray to bind to a HTML table. However the HTML table is not displaying any data. I put a label on to the HTML page and this does print out but with a toString() value of :
[Object object]
five times, which matches the amount of properties in the JSON data.
Can anyone see anything obvious I am missing?
JSON received from web server:
{ "Id": 1, "Name": "Inst123", "Price": 10, "DateTime": "2014-01-16T17:22:43.6383507+00:00", "Description": "Descriptions" };
.
ViewModel
$(document).ready(function () {
var gtViewModel = new GvTradeViewModel();
ko.applyBindings(gtViewModel);
console.log("ViewModel created");
});
var GvTradeViewModel = function () {
var self = this;
self.gvTrades = ko.observableArray([]);
var apiUrl = "http://localhost:57858/api/Trade/1";
console.log("Starting JSON data retrieval from: " + apiUrl);
$.getJSON(apiUrl)
// Handle success event.
.done(function (jsonData) {
if (jsonData.isEmptyObject)
console.log("NoData recieved");
else {
console.log("JSON data: " + jsonData);
var mappedTrades = $.map(jsonData, function (gvTradeData) {
return new GvTrade(gvTradeData);
});
self.gvTrades(mappedTrades);
console.log(self.gvTrades);
}
})
// Handle error/fail event.
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
};
function GvTrade(data) {
this.TradeId = ko.observable(data.TradeId);
this.InstrumentName = ko.observable(data.InstrumentName);
this.DateTime = ko.observable(data.DateTime);
this.Price = ko.observable(data.Price);
this.Description = ko.observable(data.Description);
}
HTML
<table>
<thead>
<tr>
<th>TradeId</th>
<th>InstrumentName</th>
<th>Price</th>
<th>DateTime</th>
<th>Description</th>
</tr>
</thead>
<tbody data-bind="foreach: $data.gvTrades">
<tr>
<td data-bind="text: InstrumentName"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: DateTime"></td>
<td data-bind="text: Description"></td>
</tr>
</tbody>
The JSON coming from your server represents a single object and not an array.
So when you are calling $.map then it does not correctly maps your data as an array, so you will end up some unusable objects.
To fix this you need to make sure that your jsonData containing an array before the map operation, you can do this with calling jQuery.makeArray on it (or you can have an if which is based on your data type decide whether you need to map or not):
var mappedTrades = $.map($.makeArray(jsonData), function (gvTradeData) {
return new GvTrade(gvTradeData);
});
Demo JSFiddle.