I have a table containing this kind of information
I am using knockout js and putting all data on a array and putting it on this table like this.
self.allchildrendata = ko.observableArray();
self.viewAllUserChildrenCard = function () {
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/childrenCardInfo',
contentType: 'application/json; charset=utf-8',
dataType :'json'
})
.done(function(childrencards) {
self.allchildrendata.removeAll();
$.each(childrencards, function (index, childrencard) {
self.allchildrendata.push(childrencard);
console.log(self.allchildrendata());
});
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.viewAllUserChildrenCard();
So next I want to click the add money button for rebecca and want to send the orig id of only rebecca so I can use it to find her in the database and add money, But i am not sure on how to send the orig_id, I tried this way.
self.giveCashtoChild = function(){
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/addUserChildrenCash' + "/" + self.allchildrendata().orig_id ,
contentType: 'application/json; charset=utf-8'
})
.done(function() {
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
}
Here is the html code where I have a databind on each of the buttons so I can send the orig id .
<tbody data-bind="foreach: allchildrendata">
<tr>
<td class="text-center"><span data-bind="text : $data.children_name"></span></td>
<td class="text-center"><span data-bind="text : $data.daugther_son"></span></td>
<td class="text-center"><span data-bind="text : $data.amount"></span> $</td>
<td class="text-center"><span class=" glyphicon glyphicon-send"></span></td>
<td class="text-center"><span class=" glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
So basically I need help to identify which family memeber I am clicking and sending that family memebers orig_id
Whenever you use a click binding, knockout passes the current binding's data and event.
So in your HTML:
<a href="#" data-bind="click : $root.giveCashtoChild">
It calls giveCashToChild with two arguments. Your giveCashToChild method should thus accept two arguments, of which the first will be the child to give cash to.
self.giveCashtoChild = function(data, event) {
var currentChildId = data.orig_id;
// the other stuff..
};
Related
I am trying to send the data of my table with dynamic values to the controller.
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td class="AutoId">#item.AutoID <input type="hidden" name="AutoID" value="#item.AutoID" /></td>
<td class="hove" name="text"> <b>#item.Text</b><br /><label></label></td>
<td class="Active">#item.Active</td>
<td id="oBy" name="OrderBy">#item.OrderBy</td>
</tr>
}
}
above is the table structure
I am using below ajax call to send one field for example...
<script>
$(document).ready(function () {
alert("Test 1");
$("#btnSave").click(function (e) {
alert("Test 2");
$.ajax({
type: "POST",
url: '#Url.Action("LookupManagementUpdate", "Admin", new { Area = "Admin" })',
data: $(".hove").val(),
dataType: 'json',
async: false,
success: function (response) {
Success = true;
},
error: function (response) {
},
});
});
});
</script>
Below is my controller code
public string LookupManagementUpdate(string text)
{
return "answer"+Request["text"]+text;
}
I tried using both Request and parameter method to fetch the data but it does not display the table data.
This is a c# mvc ado.net based project
try using Ajax.BeginForm and ajaxOptions Onsuccess
What I usually do is grab the data from the repository and pass that data along to the view via addAttribute, like this:
#GetMapping("html_page")
public String dynamicPage(Model model){
List<MySqlDataDTO> mySqlDataDTO = mySqlRepository.findAllByName(name);
model.addAttribute("mySqlDataDTO", mySqlDataDTO);
return "html_page";
}
Then use thymeleaf to loop through the data and display it in a table, like this:
<table id="table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Fav</th>
</tr>
</thead>
<tbody >
<tr th:each="mySqlDataDTO : ${mySqlDataDTO}" >
<th th:text="${mySqlDataDTO.id}"></th>
<td th:text="${mySqlDataDTO.name}"></td>
<td th:text="${mySqlDataDTO.fav}"></td>
</tr>
</tbody>
</table>
This is all fine but, the issues comes up when the user intially sends the data to the DB, the page would refresh and force the user to the top of the page thus creating a negative user experience.
I figured out how to use ajax to fix the issue of the refreshing page by having the post request go through ajax first like so:
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
Which works just fine by sending the data to the DB and not having the page refresh, but the issue is the retrieval of the data after its been sent to the database. I dont quite understand how to then retrieve the data and have it be displayed in a table to the user, here's what I have so far, but doesnt seem to work:
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
$('#table').empty();
$.each(data.items, function(item) {
alert(data.name);
});
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I added an alert just to see the data as a test. Basically I want to grab the data from the DB like I normally do via my repository, then pass that data to the view to be displayed like this:
But again it should use ajax get, so as soon the user hits submit that table refreshes (not the whole page) and the table reflects the DB data.
This is my first time posting a question so please forgive me ignorance.
Overview: I am currently pulling SharePoint 2013 list data using a REST pull to return JSON data. Below is my JS and HTML.
Problem: I need to filter the data to only display the items which were created by user who is logged in. The end result I am working towards is a page where only the items created by the user who is logged in are displayed in a table.
JS:
var myAngApp = angular.module('SharePointAngApp', []);
myAngApp.controller('spCustomerController', function ($scope, $http){
$http({
method: 'GET',
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('ITEquipmentRequests')/items?$select=*",
headers: { "Accept": "application/json;odata=verbose"}
}).success(function (data, status, headers, config) {
$scope.customers = data.d.results;
}).error(function (data, status, headers, config) {
});
});
HTML:
<div ng-controller="spCustomerController">
<table id="requestTable" class="table table-hover table-bordered">
<tr id="requestTableHeader">
<th>Name</th>
<th>Supervisor</th>
<th>Section Chief</th>
<th>ISO</th>
<th>Pentad</th>
<th>FCIO</th>
<th>Status</th>
</tr>
<tr ng-repeat="customer in customers">
<td class="col-md-4"><a ng-href="/PHX_IRM/ITEquip/ITEquipmentRequests/{{customer.Title}}">{{customer.Title}}</a></td>
<td class="col-md-1"><img class="statusIcon" src="{{customer.TextPicture}}" alt="Status"></td>
<td class="col-md-1"><img class="statusIcon" src="{{customer.SectionChief}}" alt="Status"></td>
<td class="col-md-1"><img class="statusIcon" src="{{customer.ISO}}" alt="Status"></td>
<td class="col-md-1"><img class="statusIcon" src="{{customer.Pentad}}" alt="Status"></td>
<td class="col-md-1"><img class="statusIcon" src="{{customer.FCIO}}" alt="Status"></td>
<td class="col-md-2">{{customer.Status}}</td>
</tr>
</table>
</div>
Any Help would be greatly appreciated. Thank you for your time.
You could consider the following options:
Filter list items via CAML query
Filter list items via CAML query. Only the items that satisfy the query will be returned from the server, for that purpose replace the request:
$http({
method: 'GET',
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('ITEquipmentRequests')/items?$select=*",
headers: { "Accept": "application/json;odata=verbose"}
})
with
//request endpoint
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
//construct CAML query to return list items created by current user
var queryXml = "<View><Query><Where><Eq><FieldRef Name='Author' LookupId='True'/><Value Type='Lookup'>" + _spPageContextInfo.userId + "</Value></Eq></Where></Query></View>";
//query payload
var queryPayload = {
'query':{
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml': queryXml
}
};
$http({
method: "POST",
url : endpointUrl,
data: queryPayload,
headers: {
"Content-Type" : "application/json;odata=verbose",
"Accept": "application/json;odata=verbose",
"X-RequestDigest": document.getElementById('__REQUESTDIGEST').value
}
})
Explanation:
CAML query is invoked via POST reqest using the following endpoint:
/_api/web/lists/getbytitle('<listTitle>')/getitems
From performance perspective it represents the best approach.
Using Angular filter
Replace the line:
<tr ng-repeat="customer in customers">
with
<tr ng-repeat="customer in customers | filter : isCurrentCustomer">
and declare isCurrentCustomer function in controller like this:
$scope.isCurrentCustomer = function(customer){
return (customer.AuthorId == _spPageContextInfo.userId);
}
If you want to filter the results on client side, you can use the angular filter in your repeater.
<tr ng-repeat="customer in customers | filter : customer == loggedInUser">
I'm making ajax table with Node.js. I can update the rows without refreshing whole page, and delete task also. it's not perfect because of below reason, please see the image.
When I update some row, and I click 'remove' button, it is not working. But after I refresh the whole page, it works well. Maybe this is very verbose question, If you have not enough time - please see js file, there is key of problem... Okay, then the codes are :
html : If I load page, the page will find database and show each one. No problem with this I think.
<table id="tb-docs">
<thead>
<tr>
<th width="50">Active</th>
<th width="300">Subject</th>
<th>Content</th>
<th width="110">Action</th>
</tr>
</thead>
<tbody>
<% posts.forEach( function ( post, index ){ %>
<tr>
<td><input type="checkbox"/></td>
<td><%= post.Subject %></td>
<td><%= post.Content %></td>
<td><button onclick="deleteRow(this,'<%= post._id %>')">Remove</button>
</td>
</tr>
<% }); %>
</tbody>
</table>
js : I strongly suspect 'append()' in updateRow function. maybe there is something wrong,
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow('+this+','+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
server (node.js)
// update row handler ===============
app.post('/', function (req, res){
new posts({
Subject: req.body.subject,
Content: req.body.content,
Active: true
}).save(function (err, post) {
if (err) return next(err);
res.send(post._id);
});
});
// delete row handler ===============
app.post('/dbs/destroy/:id',function (req, res){
posts.findById(req.params.id, function (err, post){
if (err) res.send(err) ;
post.remove(function(err, todo, next){
if(err) return next(err);
res.sendStatus(200);
});
});
});
I struggled with it for 2 days. This appending row in table is just trick, right? So I think appended 'button' is not worked, but reloaded page 'button' is worked. Then, How can I do action with appended button?
I think a other way, separate this table html file and ajax get call. but I have a lot of tables, so this is very hard works and not efficient way. Could you tell me what is real problem? Sorry for no fiddle because it is related with database. Anyway Thanks for reading.!
Instead of using '+this+' just type this in the onclick function for the deleteRow button.
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow(this,'+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
Using the following code i experience a strange problem. When I click and call showVacationModal data is retrieved fine from the server and result is displayed correctly. If i keep clicking the same person(id) it continues to work.
If I click a different person (eg. different id) with no vacations nothing is showed = OK.
The problem
Now when I click the first person again nothing is displayed. (data is retrieved fine in ajax call).
Any ideas?
My JS code:
var ViewModel = function () {
this.vacations = ko.mapping.fromJS(null);
};
var model = new ViewModel();
function showVacationModal(id) {
var model = {};
$.ajax({
type: "POST",
url: "Default.aspx/GetVacations",
data: "{personId: '" + id + "'}",
delay: 1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
model.vacations = ko.mapping.fromJS(msg.d);
ko.applyBindings(model);
$('#vacationModal').modal('show')
}
});
}
My HTML:
<table>
<thead>
<tr>
<th>
First name
</th>
<th>
Last name
</th>
</tr>
</thead>
<tbody data-bind="foreach: vacations">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: PersonId">
</td>
<td data-bind="text: Begin">
</td>
</tr>
</tbody>
</table>
Have you tried something more like this?
function showVacationModal(id) {
// var model = {}; no need to reset the model property
$.ajax({
type: "POST",
url: "Default.aspx/GetVacations",
data: { personId: id }, // why wrap data in strings?
delay: 1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//model.vacations = ko.mapping.fromJS(msg.d);
ko.mapping.fromJS(msg.d, {}, model.vacations);
// ko.applyBindings(model); no need to reapply bindings
$('#vacationModal').modal('show')
}
});
}
See this ko.mapping documentation section for more information.