JqGrid checkbox, Controller retrieve null instead of int - ajax

I have a jqgrid with a checkbox column. when checkbox is pressed i need to update database.
I can retrieve id from my jqgrid, but when I'm sending it further to my controller I retrieve id = null
here is the code in load complete function
var iCol = getColumnIndexByName($(this), 'Aktiv'), rows = this.rows, i,
c = rows.length;
for (i = 0; i < c; i += 1) {
$(rows[i].cells[iCol]).click(function(e) {
var id = $(e.target).closest('tr')[0].id,
isChecked = $(e.target).is(':checked');
alert('clicked on the checkbox in the row with id=' + id +
'\nNow the checkbox is ' +
(isChecked ? 'checked' : 'not checked'));
$.ajax({
mtype: "POST",
url: '#Url.Action("Action")',
data: { actionparameter: id },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false
});
;

if alert shows not null for the id you should verify your server code. Depend on your configuration you could need to use JSON.stringify method from json2.js like
data: JSON.stringify({actionparameter: id})
or just do no JSON specific prameters in the $.ajax call.

Related

What is the correct way of reading from 2 endpoints and displaying it in 1 table using ajax?

I have 2 tables(endpoints) - users and leaderboard. In users table their are columns user_id and full_name. In leaderboard table there is a user_id column and other columns. I want to display leaderboard table. But instead of user_id I want to show full_name column.
So I will have to take the full_name from the users table. This is my code:
1st ajax call -
var users = [];
$.ajax({
url: url + "admin/users",
type: "GET",
dataType: 'json',
async: false,
crossDomain: true,
success: function (result){
for (i=0; i < result.data.length; i++) {
users[i] = result.data[i];
}
}
})
2nd ajax call -
$.ajax({
url: url + "admin/leaderboard",
type: "GET",
dataType: 'json',
async: false,
crossDomain: true,
success: function (result){
for (i=0; i < result.data.length; i++) {
var row = document.getElementById("table-body").insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
for (j=0 ; j < users.length ; j++) {
if (result.data[i].user_id === users[j]._id) {
cell1.innerHTML = users[j].full_name;
break;
}
else {
cell1.innerHTML = 'NA';
}
}
cell2.innerHTML = result.data[i].points;
}
$('#dataTable').DataTable();
}
})
The 2nd ajax call occurs only after the 1st ajax call is completed.
Right now I have only 15 rows in the users table. But later on there will be thousands of rows. If there are thousands of rows in the users endpoint then the 1st ajax call will take a long time to complete. It will have detrimental effects to the end user's experience. So what would be the correct way of coding it?
The code is working fine. The only issue is the speed.

Ajax not working propperly on first click

I have this of code that will show the data on a modal when a button click :
$("#editItem").on('show.bs.modal', function(e) {
$("#editAlert").attr("class", "d-none");
$("#editNoChanges").attr("class", "d-none");
var serialNo = $(e.relatedTarget).data('item-id');
console.log(serialNo); //Serial Key
$(e.currentTarget).find('input[name="productSerialEdit"]').val(serialNo);
$.ajax({
type: 'POST',
url: 'getItemInfo.php?serialNo='+serialNo,
data: {
serialNo: serialNo
},
dataType: 'json',
success: function(edit) {
var trig = "edit";
var nameEdit = $("#productNameEdit option[value='"+edit[0]+"']").prop('selected', true);
var typeEdit = $("#productTypeEdit option[value='"+edit[1]+"']").prop('selected', true);
var locEdit = $("#productLocationEdit option[value='"+edit[2]+"']").prop('selected', true);
$("#productPriceEdit").attr("value", edit[3]);
populateSelect(trig, nameEdit, typeEdit, locEdit);
console.log("Editting ..");
console.log($(nameEdit).val());
console.log($(locEdit).val());
console.log($('#productPriceEdit').val());
}
});
});//Edit Funtion End
the problem is that, on first click, its not showing the right data, i have to click the button/show the modal 2nd time to show the correct data, what could be the problem or solution for this ?

jqgrid onclickSubmitLocal using ajax

I am using the example here as a starting point. Everything works fine, I can submit the data back to the server and get a response. However I don't know how to connect the callback from the ajax to the jqgrid onclickSubmitLocal. I don't want to use alerts because even if there is an error the row is updated. I would like some how if there is an error the modal edit dialog to show the error and prevent it from updating the row. On success I would like the user to get a message saying data was saved.
Here is the relevant code:
function submitData(rowData){
var dataToSend = JSON.stringify(rowData);
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: dataToSend,
dataType: 'json',
success: function (result) {
alert(' successfully saved.');
},
error: function(xhr, status, error) {
alert('Error processing submit ' + xhr.responseText);
}
});
}
I called the previous function from
onclickSubmitLocal = function (options, postdata) {
var $this = $(this), p = $(this).jqGrid("getGridParam"),// p = this.p,
idname = p.prmNames.id,
id = this.id,
idInPostdata = id + "_id",
rowid = postdata[idInPostdata],
addMode = rowid === "_empty",
oldValueOfSortColumn,
newId,
idOfTreeParentNode;
... same as in example from link above
if (postdata[p.sortname] !== oldValueOfSortColumn) {
// if the data are changed in the column by which are currently sorted
// we need resort the grid
setTimeout(function () {
$this.trigger("reloadGrid", [{current: true}]);
}, 100);
}
// !!! the most important step: skip ajax request to the server
options.processing = true;
submitData([postdata]);
},

CFWheels Pagination using AJAX

I've searched the entire Internet, all of it, and cannot find an answer to this.
I'm using the ColdFusion CFWheels Framework to query a database. The query is done via AJAX like this:
var id = $("#ship-id").val();
$.ajax({
type: "POST",
url: "/my-controller/my-method?format=json",
data: {shipId: id},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, value) {
resultHtml += '<tr><td>' + value.FIRSTNAME + ' ' + value.LASTNAME + '</td></tr>';
});
$("#my-table").html(resultHtml);
}
});
I need to paginate that result set. In CFWheels you normally do that by setting the handle, page, perPage and order values in the query like this:
var order = model("order").findAll(
select="id, firstname, lastname, email",
where="orderid IN (#ValueList(orders.id)#)",
handle="ordersQuery",
page=params.page,
perPage=5,
order="lastname"
);
Then you just put this line in your view:
<cfoutput>#paginationLinks(handle="ordersQuery")#</cfoutput>
But... how in the heck can you get pagination to work with an AJAX call?
I think that something along these lines might be your answer (notice I removed the url and added those params to data ...
$.ajax({
type: "POST",
data: {
shipId: id,
controller: myController,
action: myAction,
page: params.page,
},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, value) {
resultHtml += '<tr><td>' + value.FIRSTNAME + ' ' + value.LASTNAME + '</td></tr>';
});
$("#my-table").html(resultHtml);
}
});

jQuery mobile cascading dropdown list do not update properly

I'm using cascading drop down lists in my MVC application, and it works fine.
I have added the jQuery mobile library to make it look better in mobile devices browser and I have kind of bug.
An example:
if I choose first time Chevrolet it populate child drop down with Chevrolet models. - as expected
if I choose second time another make I still see the models from previous make, but if I select it I see the new model. It looks like it cashing the models from previous make.
Here is my code:
$(document).ready(function () {
$('select#Makes').change(function () {
getModels();
});
});
function getModels() {
var make = $('#Makes').val();
var myselect2 = $("select#Models");
myselect2[0].selectedIndex = 3;
myselect2.selectmenu("refresh");
$.ajax({
type: "POST",
url: "/Services/CarService.asmx/Models",
data: "{makeId: '" + make + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var models = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#Models').attr('disabled', false).removeOption(/./); //.addOption('', ' -- Select Model -- ');
var select = document.getElementById("Models");
for (var i = 0; i < models.length; i++) {
var val = models[i];
var text = models[i];
$('select#Models').addOption(val, text, true);
}
var myselect = $("select#Models");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
}
});
}
#Html.DropDownList("Makes", "Please select make")
#Html.DropDownListFor(x => x.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "value", "text"), "Select a Model", new { id = "Models" })

Resources