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();
}
});
});
Related
I'm trying to understand how to remove an item from my Firebase. I've set up a function (saveEmployee) to create an item , but can't figure out how to go about removing an item.
HTML
<tbody ng-repeat="employee in employees">
<tr>
<td>{{employee.employeeName}}</td>
<td>{{employee.employeeAge}}</td>
<td><a class="btn btn-danger" ng-click="removeEmployee(employee.employeeName)" >Delete</a></td>
</tr>
</tbody>
JS
$scope.removeEmployee = function(employeeName) {
console.log(employeeName);
$scope.myData.child(employeeName).remove();
};
Use Firebase.set() and pass in null. This will delete the employee.
$scope.removeEmployee = function(employeeId) {
var employeeRef = new Firebase('https://myfirebaseurl.firebaseio.com/employees/' + employeeId);
employeeRef.set(null);
};
or with a callback handler.
$scope.removeEmployee = function(employeeId) {
var employeeRef = new Firebase('https://myfirebaseurl.firebaseio.com/employees/' + employeeId);
employeeRef.set(null, function(error) {
if (error) {
console.log(error);
} else {
console.log('Employee deleted.');
}
});
};
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?
I am trying to fetch the data from files using Ajax by clicking row of table (passing row values to button on clicking rows) or by entering the variables in text box and pressing button. But it does not seem to be working.(Pls don't downvote as i am C++ programmer and learning web development.)
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<table bodrder=1 class='list'>
<thead>
<tr>
<th class='A'>ID</th>
<th class='B'>Value</th>
<th class='C'>Name</th>
<th class='D'>Cell #</th>
<th class='E'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>54235</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
<tr>
<td>2</td>
<td>44235</td>
<td>XXXXXX</td>
<td>642363673</td>
<td>TRE</td>
</tr>
</tbody>
</table>
<div id="tabs" class="plots-tabs" style="padding-top: 10px; padding-bottom: 10px">
<table>
<tr><td>ID:<input id="id" type="text" class="inputbox" /></td></tr>
<tr><td>Value:<input id="value" type="text" class="inputbox" /></td></tr>
</table>
This is DIV element which will be filled by div element on clicking button or by clicking table row which also generate the event and click the button by passing values to ajax and fetchign data.
<p style="width: 100%; text-align: right;"><button type="button" id="button">Submit</button></p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//here ID and value are parsed through table click event or from text box on clicking button
$.ajax({
url:filename,
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
},
success:function(result){
$("#tabs").html(result);
}});
var filename= "Data_"+ID+"_"+Value+".txt";
$("#tabs").load(filename);
});
});
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < 2; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
</script>
</body>
</html>
cat Data_2_54235.txt
Nice Work! Your code is working with first file.
cat Data_2_44235.txt
Nice Work! Your code is working with second file.
how can i implement the above code.
I see you generate a filename based on input values. That means that the ajax call will be made upon that filename, which is odd, becouse you have to create a file with that name.
Anyway, i don't see nowhere in your code that by clicking table rows you make an ajax call, you only save the innerHTML text to a variable data = [] and then alert it. But the problem is not here (if you don't expect to make ajax call when clicking table-rows), but it is inside the ajax call you are making when clicking the button.
first
url:filename
var filename= "Data_"+ID+"_"+Value+".txt";
I strongly suggest you don't do that. It will work if you make an ajax call to a php script which creates that txt file with filename name, and then make another ajax call to that file and fetch it.
second
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
}
look here at data, the doc explains it. the code above means that to filename it will pass parameters (GET parameters, i.e. x?=...), but becouse your file is .txt, this doesn't make sense.
third
$("#tabs").load("demo_test.txt");
This will add the text inside demo_test.txt to $("#tabs") , like innerHTML does or .html() does. Do you have demo_test.txt on your host? i suppose this should work.
just change you ajax call and load call with this. this should work :
$("button").click(function() {
$.ajax({
url : "demo_test.txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
}
});
});
For clicking the table-rows, just add an event listener to table-rows, and make an ajax call. read the link i send you, as they are important to understand better what is ajax.
You can see no unnecessary data parameter is thrown to ajax call, and i put there an dataType, meaning that we expect text data to be recieved. If this doesn't work, you have to be sure that you are working on localhost server(for ajax to work...) and you have demo_test.txt , and the url is passed correctly
example using input values to fetch from ajax:
$("button").click(function() {
var id = $("input#id").val();
var value = $("input#value").val();
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
example of event handler click <tr>
$("table tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the clicked tr (this is the ID i suppose)
var value = $(this).find("td")[1].text(); // gets the second td of the clicked tr (this is the VALUE i suppose)
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
I want to change user status in my system. Before change the status i need show confirmation box. So i add bootstrap model for it like follows.
html
<tbody>
<tr>
<td>Dinuka Perera</td>
<td>User is active</td>
<td>Activate</td>
</tr>
<tr>
<td>Thilanga Perera</td>
<td>User is inactive</td>
<td>Dectivate</td>
</tr>
<tr>
<td>Test Perera</td>
<td>User is active</td>
<td>Activate</td>
</tr>
</tbody>
js
$(document).on('click','.active', function () {
var $this = $(this);
$('#status-model').modal();
$('.alert').remove();
$('#change-btn').click(function() {
var id = $this.parents('tr').data('id');
$.post('users/status', {id:id, status:0}, function( data ) {
var obj = $.parseJSON(data);
if (obj.success != undefined) {
$this.html('Activate');
$this.removeClass('active');
$this.addClass('inactive');
$this.parents('tr').find('.status').html('User is inactive');
$('#search-form').before('<div class="alert alert-success">User activation successful</div>');
$('#status-model').modal('hide');
}
});
});
});
$(document).on('click','.inactive', function () {
var $this = $(this);
$('#status-model').modal();
$('.alert').remove();
$('#change-btn').click(function() {
var id = $this.parents('tr').data('id');
$.post('users/status', {id:id, status:1}, function( data ) {
var obj = $.parseJSON(data);
if (obj.success != undefined) {
$this.html('Deactivate');
$this.removeClass('inactive');
$this.addClass('active');
$this.parents('tr').find('.status').html('User is active');
$('#search-form').before('<div class="alert alert-success">User deactivation successful</div>');
$('#status-model').modal('hide');
}
});
});
});
It is working for fist time. After that it will send multiple ajax request. It was successful before i add this model. What is the issue?
When you click .active or .inactive object it bind an event to "#change-btn" object. Therefore each of binded click event send another ajax request to server. Therefore you have to remove all click event before binding. You can do that like;
$( "#change-btn").unbind( "click" );
$('#change-btn').click(function() {
...
});
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.