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.
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
I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls.
My view:
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def getfromServer(request):
if is_ajax(request=request) and request.method == "GET":
books= Book.objects.all()
bookserial = serializers.serialize('json', books)
return JsonResponse(bookserial, safe=False)
return JsonResponse({'message':'Wrong validation'})
index.html
<div class="container">
<table id="books" class="display" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Author</th>
<th>Genre</th>
<th>Date Publishedd</th>
<th>Copies</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function() {
$('#books').DataTable({
ajax: {
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
},
columns: [
{ data: 'name' },
{ data: 'author' },
{ data: 'genre' },
{ data: 'pub_date' },
{ data: 'copies' },
]
});
</script>
Im pretty sure it kinda works this way but i just cant figure it out .
jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library
So it doesn't make sense to put an ajax request inside the .DataTable() method
You have to make the ajax request first:
$.ajax({
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
success: function (result) { // result is the response you get from the server if successful
// Use the data in result to write the values to your html table respectively here
}
error: function (err) {
// handle error
}
})
thats what I came up with but still doesnt seem to do the trick all i get is an empty table .
$.ajax({
type: "GET",
datatype : 'json',
url: "views/getfromServer", // "{% url 'index' %}"
success: function (response) {
var instant = JSON.parse(response[books]);
for book in books {
var fields= instant[book]["fields"];
$("#books tbody").prepend(
`<tr>
<td>${fields["name"]||""}</td>
<td>${fields["author"]||""}</td>
<td>${fields["genre"]||""}</td>
<td>${fields["pub_date"]||""}</td>
<td>${fields["copies"]||""}</td>
</tr>`
)
}
},
error: function (response) {
alert(response["responseJSON"]["error"]);
}
})
$(document).ready(function() {
$('#books').DataTable();
Below is the view modal where I am getting the ajax response and load to the obserable value.
var userManagementVM = {
responseSetUpData: ko.observable({
userList: ko.observable(),
userListViewModel: ko.observableArray(),
MeetingId: ko.observable(),
MeetingTypeId: ko.observable(),
MeetingType: ko.observable()
}),
SetListOfUserInRoles: function () {
var self = this;
var ajaxUrl = ApplicationRootUrl("UserRoleManagement", "UserManagement");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: ajaxUrl,
dataType: "json",
success: function (data) {
self.responseSetUpData(data);
console.log(self.responseSetUpData())
},
error: function (err) {
}
});
}
}
$(document).ready(function () {
ko.applyBindings(userManagementVM, document.getElementById("rightdash-container"));
userManagementVM.SetListOfUserInRoles();
});
The response from the ajax is successfully loaded to the obserable value. Below is the output of the console
HTML code
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Users</th>
<th scope="col">Role</th>
</tr>
</thead>
<tbody data-bind="foreach: responseSetUpData.userListViewModel">
<tr>
<td><input class="form-check-input" type="checkbox" data-bind="checked: SelectedUser"><span data-bind="text: $data.FirstName"></span></td>
<td><select data-bind="options: $data.Roles,optionsText: 'Name',value: $data.SelectedRoleId,optionsCaption: '-- Select Role --'"></select></td>
</tr>
</tbody>
</table>
The value is not bind to the UI.
You need to get the value of the observable - responseSetUpData() in the binding:
<tbody data-bind="foreach: responseSetUpData().userListViewModel">
Otherwise you are trying to get userListViewModel from the observable function object :-)
In dropdownlist onchange event call FillSystem() Ajax Request is sent but scopeId selector do not run this below method.
function FillSystem() {
var _scopeId = $('#ScopeId').val();
var _roleId = $('#Role_Id').val();
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId").html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId").append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
<table class="table w3-striped w3-border w3-card-4" style="width: 65%">
<tr>
<td>
Scope
</td>
<td>
#Html.DropDownList("ScopeId", null,"--Please Select--", new { style = "width:250px", #onchange = "FillSystem()" })
</td>
</tr>
<tr>
<td>System</td>
<td>
#Html.DropDownList("SystemId", null, "--please select--", new { style = "width:250px" })
</td>
</tr>
</table>
you use DropDown in table and probably multiple row exist, and multiple id with same, your $('#ScopeId') selector, select first element with ScopeId.
first remove #onchange = "FillSystem()" from DropDownList, then try this code
(function ($) {
function FillSystem() {
var _scopeId = $(this).val();
var _roleId = $('#Role_Id').val();
var $row = $(this).closest("tr");
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId", $row).html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId", $row).append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
$(function () {
$("table").on("change", "#ScopeId", FillSystem)
});
}(jQuery));
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..
};