AJAX post data to DB without ASP:button - javascript

I retrieve a value in js and i want to insert it in the DB with ajax post. Is it possible to do that without asp:button to bind the value to the code behind?
UPDATE here is the Js:
function readXML() {
var xml = new XMLHttpRequest();
xml.open('GET', 'toXml/file.xml', false);
xml.send();
var xmlData = xml.responseXML;
if (!xmlData) {
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
}
var itemsID = xmlData.getElementsByTagName("entry");
var itemsTitle = xmlData.getElementsByTagName("entry");
var itemsCustomer = xmlData.getElementsByTagName("d:Customer");
var itemsBrand = xmlData.getElementsByTagName("d:Brand");
var itemsCountries = xmlData.getElementsByTagName("d:Countries");
var itemsElement = xmlData.getElementsByTagName("d:element");
var i, k, j, ID, Title, Customer, Brand, Countries;
var list = [];
for (i = 0; i < itemsTitle.length; i++) {
var Brands = "";
var Country = "";
itemI = itemsID[i];
itemT = itemsTitle[i];
itemCr = itemsCustomer[i];
itemB = itemsBrand[i];
itemCs = itemsCountries[i];
itemEl = itemsElement[k];
ID = itemI.getElementsByTagName("d:Id")[0].firstChild.data;
Title = itemT.getElementsByTagName("d:Title")[0].firstChild.data;
Customer = itemCr.getElementsByTagName("d:element")[0].firstChild.data;
for (k = 0; k < itemB.children.length; k++) {
Brand = itemB.getElementsByTagName("d:element")[k].firstChild.data;
if (k > 1) {
Brands += Brand + ",";
}
else {
Brands = Brand;
}
}
for (j = 0; j < itemCs.children.length; j++) {
Countries = itemCs.getElementsByTagName("d:element")[j].firstChild.data;
if (j > 1) {
Country += Countries + ",";
}
else {
Country = Countries;
}
}
list[i] = [ID, Title, Customer, Brands, Country];
}
var table = $('#table_id').DataTable({
lengthMenu: [[10, 25, 50, 200, -1], [10, 25, 50, 200, "All"]],
data: list,
columns: [
{ title: "ID" },
{ title: "Title" },
{ title: "Customer" },
{ title: "Brands" },
{ title: "Country" },
{ title: "Check", "defaultContent": "<button class=\"checkBtn\" type=\"button\">Check</button>" },
{ title: "Create", "defaultContent": "<button class=\"createBtn\" type=\"button\">Create</button>" }
],
columnDefs: [{
"targets": [0],
"visible": true,
"searchable": true
}]
});
$('#table_id').on('click', '.checkBtn', function () {
var data = table.row($(this).parents('tr')).data();
alert("ID:" + data[0] + "," + "Title:" + data[1] + "," + "Customer:" + data[2] + "," + "Brand:" + data[3] + "," + "Country:" + data[4]);
$.ajax({
type: "POST",
url: "Selida.aspx/InsertData",
data: JSON.stringify(data[0]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("all good");
},
error: function (errMessage) {
alert("Error:" + errMessage);
}
});
});
}
Through C# im getting data and i save it into an xml file. Then with the js i retrieve that data and with Jquery datatables im displaying on the page.
I Have a method in c# called InsertData which is supposed to insert the data in the DB. I think that the problem is in the ajax call.

The answer is yes, i can post a value from js with an ajax call that has no relation with the server side
$.ajax({
type: "POST",
url: "Selida.aspx/CheckData",
data: JSON.stringify({ trala : data[0] }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("It's already in the DB");
},
error: function (errMessage) {
console.log("Error:" + JSON.stringify(errMessage));
}
});
and the parameter in the c# method must have the name "trala" in order to retrieve the value from the post.

Related

Using the content of a variable returned by DataTables in another part of the script

How can I use the "DeviceID" in the "columns:" in another part of the script. I have tried all manner of things like re positioning some of the code but no matter what I do I can't get it to work.
I need to use the "DeviceID" as a variable in
"url: 'get_wayfinder_offline_status.php', data: { DeviceID: deviceid },"
Look at << USE THIS IN PART MARKED "HERE"
$(document).ready(function() {
var table = $('#WayFinderStatusTable').DataTable({
ordering: false,
paging: false,
searching: false,
bInfo: false,
responsive: true,
fixedHeader: true,
scrollX: false,
pageResize: true,
ajax: {
url: 'check_wayfinder_status.php',
dataSrc: ''
},
columns: [{
data: 'DisplayDescription',
"sWidth": "100%"
},
{
data: 'DeviceName',
"visible": false
},
{
data: 'MessageCount',
"visible": false
},
{
data: 'BoardOverride',
"visible": false
},
{
data: 'DeviceID',
"visible": false
}, // << USE THIS IN PART MAKED "HERE"
],
rowCallback: function(row, data, dataIndex) {
if (data.MessageCount == 2) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
} else if (data.BoardOverride == 1) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOverrideOn ');
$('#WayFinderStatusTable tbody').on('click', 'tr', function() {
var hotelid = "<?php echo $_SESSION['_amember_user']['hotelid'];?>";
var data = table.row(this).data();
var deviceid = data.DeviceID;
console.log("DEVICE ID", deviceid);
$.ajax({
url: 'get_wayfinder_override_status.php',
data: {
DeviceID: deviceid
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
console.log("BoardName", result);
$('#EditOverrideWayfinderRecordID').val(result[0]);
$('#EditOverrideWayfinderBoardName').val(result[1]);
var testimage = result[2];
console.log("TEST IMAGE", testimage);
$('#EditOverrideWayfinderImage').val(result[2]);
var imagepath = '../../../../conf/conf_images/override/' + hotelid + '/' + result[2];
$("#EditOverrideWayfinderLookUpCompanyImage").attr("src", imagepath);
$("#EditOverrideWayfinderImagePreview").attr("src", imagepath);
$('#EditOverrideWayfinderRoomFromDate').val(result[3]);
$('#EditOverrideWayfinderRoomFromTimeH').val(result[4]);
$('#EditOverrideWayfinderRoomFromTimeM').val(result[5]);
$('#EditOverrideWayfinderRoomToDate').val(result[6]);
$('#EditOverrideWayfinderRoomToTimeH').val(result[7]);
$('#EditOverrideWayfinderRoomToTimeM').val(result[8]);
$('#EditOverrideWayfinderPromotionName').val(result[9]);
$('#EditOverrideWayfinderHardwareID').val(result[10]);
$('#edit_wayfinder_override_data_modal').modal('show');
}
}
});
});
} else if (data.BoardOverride == "") {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOff');
}
},
});
$(document).on('click', '.WayFinderStatusTableOff', function(e) {
$('#wayfinder_override_data_modal').modal('show');
});
$(document).on('click', '.WayFinderStatusTableOn', function(e) {
console.log("OFFLINE CLICKED");
$.ajax({
url: 'get_wayfinder_offline_status.php',
data: {
DeviceID: deviceid //<<HERE
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
// DO SOMETHING
}
}
});
$('#offline_data_modal').modal('show');
});
setInterval(function() {
$('#WayFinderStatusTable').DataTable().ajax.reload();
}, 30000);
});
Based on structure of your datatables and column, clicked on a row the deviceId is find by using the method table.row( this ).data(); and next find the right index of the data.
$('#WayFinderStatusTable').on('click', 'tr', function () {
const data = table.row( this ).data();
const deviceId = data[4];
alert(deviceId + ' -> deviceid');
});

How to improve datatable loading performance when datatable has a rendered chart inside each column?

I have a datatable rendered with a chart on each column, the datatable generated from ajax response data having more than 1000 records. Rendering the chart inside the columns results in performance issues. How to improve the performance?
Here is the code i use:
ajax:
var resData = [];
$.ajax({
'type': "POST",
'url': "CoxModel/processTypes/execution",
'data': dataList,
'beforeSend': function() {
$(".graphloadertraining").show();
},
'success': function(data) {
response = $.parseJSON(data);
response = response.data
$.each(response, function(index, value) {
var jsonObject = JSON.stringify(response);
var count = JSON.parse(jsonObject).length;
resData.push(value);
})
variableData(resData);
// return data;
}
});
chart generate:
function variableData(data) {
$(".graphloader").hide();
var newAry = {};
var newAryy = [];
i = 0;
$.each(data, function(index, value) {
var pd = value.PROCESSDATE;
var pt = value.PROCESS_TYPE;
var mn = value.MODELNAME;
var vn = value.VARIABLENAME;
var vc = value.VARIABLECONTRIBUTION;
if (!newAry[pt]) {
newAry[pt] = {};
}
if (!newAry[pt][mn]) {
newAry[pt][mn] = {};
}
if (!newAry[pt][mn][vn]) {
newAry[pt][mn][vn] = {};
}
if (!newAry[pt][mn][vn]['pd']) {
newAry[pt][mn][vn]['pd'] = [];
}
if (!newAry[pt][mn][vn]['vc']) {
newAry[pt][mn][vn]['vc'] = [];
}
newAry[pt][mn][vn]['pd'].push(pd);
newAry[pt][mn][vn]['vc'].push(vc);
i++;
});
if ($.fn.DataTable.isDataTable("#cox-model-modelgraph-variable")) {
$('#cox-model-modelgraph-variable').DataTable().clear().destroy();
}
tableWithChart = $('#cox-model-modelgraph-variable tbody');
tableBodyContent = '';
$.each(newAry, function(pType, pTypeValue) {
$.each(pTypeValue, function(mName, mNameValue) {
$.each(mNameValue, function(vName, vNameValue) {
tableBodyContent += '<tr><td>' + pType + '</td>';
tableBodyContent += '<td>' + mName + '</td>';
tableBodyContent += '<td>' + vName + '</td>';
tableBodyContent += '<td><div id="model-graph-' + pType + '-' + mName + '-' + vName + '" data-value="' + vNameValue.pd + '|' + vNameValue.vc + '"></div></td>';
tableBodyContent += '</tr>';
});
});
});
tableWithChart.html(tableBodyContent);
$(".chartContainer").empty();
$("#cox-model-modelgraph-variable").dataTable({
pageLength: 50,
deferRender: true,
processing: true,
"columns": [{
"title": "PROCESS TYPE"
}, {
"title": "MODEL NAME"
}, {
"title": "VARIABLE NAME"
}, {
"sortable": false,
"render": function(data, type, row, meta) {
dataId = $(data).attr('id');
dataValue = $(data).data('value');
return $("<div></div>", {
"id": dataId
}).append(modelGraphVariableChart(dataId, dataValue)).prop("outerHTML");
}
}]
});
$(".graphloader").hide();
$("#cox-model-modelgraph-variable tbody").removeClass('tr-loading');
}
function modelGraphVariableChart(chartContainer, chartValue) {
chartValue = chartValue.split('|');
for (i in chartValue) {
chartValue[i] = chartValue[i].split(',');
for (j in chartValue[i]) {
if (chartValue[i][j] == '') chartValue[i][j] = 0;
else if (parseFloat(chartValue[i][j]) == chartValue[i][j]) {
chartValue[i][j] = parseFloat(chartValue[i][j]);
} else {
chartValue[i][j] = chartValue[i][j];
}
}
}
newchart[chartContainer] = Highcharts.chart(chartContainer, {
chart: {
type: 'spline',
height: 100,
scrollablePlotArea: {
minWidth: 300,
maxWidth: 300,
scrollPositionX: 1
}
},
title: {
text: null
},
subtitle: {
text: null
},
xAxis: {
categories: chartValue[0]
},
yAxis: {
labels: false,
title: {
text: null
},
endOnTick: false,
minorGridLineWidth: 0,
gridLineWidth: 1,
alternateGridColor: null,
},
tooltip: {
valueSuffix: null
},
credits: {
enabled: false
},
legend: {
enabled: false
},
series: [{
name: 'VC',
data: chartValue[1]
}]
});
return newchart;
}
My table looks like this:

translating hard coded input to variable input in api call

I'm following the Here maps examples for matrix calculator and have my working example using hard coded values. I want to translate this into usable code by looping through variables to add to the api call. I have tried many ways to do this but all result in 400 (improperely formatted call) error
the below code works (albeit when my app_code and app_id are used)
$.ajax({
url: "https://matrix.route.api.here.com/routing/7.2/calculatematrix.json",
type: "GET",
dataType: "jsonp",
jsonp: "jsoncallback",
data: {
app_code: "xxxxxxxxxxxxxx",
app_id: "xxxxxxxxxxxx",
destination0: "52.5488,-3.4974",
mode: "fastest;car",
start0: "52.7972,-3.1031",
start1: "52.5795,-3.8714",
start2: "52.5735,-3.1266",
start3: "51.9295,-2.8547",
start4: "51.9498,-3.5812",
summaryAttributes: "di,tt"
},
success: function(data, status) {
var i;
for (i = 0; i < data.response.matrixEntry.length; i++) {
alert("Start" + i + ": Distance: " + data.response.matrixEntry[i].summary.distance + " Time: " + data.response.matrixEntry[i].summary.travelTime);
}
},
error: function(data) {
alert("error encountered trying to get mileage");
}
});
my attempt below doesn't work
var sourceLocations = [{
lat: "52.7972",
lng: "-3.1031",
title: "Source_1",
distance: 0
}, {
lat: "52.5795",
lng: "-3.8714",
title: "Source_2",
distance: 0
}, {
lat: "52.5735",
lng: "-3.1266",
title: "Source_3",
distance: 0
}, {
lat: "51.9295",
lng: "-2.8547",
title: "Source_4",
distance: 0
}, {
lat: "51.9498",
lng: "-3.5812",
title: "Source_5",
distance: 0
}];
var myData = "{\"app_code\":\"J_lS80f2OSqMMDWFy2ZOmA\",\"app_id\":\"J_lS80f2OSqMMDWFy2ZOmA\",";
myData = myData + "\"destination0\":\"52.5488,-3.4974\",";
myData = myData + "\"mode\":\"fastest;car\",";
// loop thru source locations
var i;
for (i = 0; i < sourceLocations.length; i++) {
var ele = "\"start" + i + "\":";
myData = myData + ele + "\"" + sourceLocations[i].lat + "," + sourceLocations[i].lng + "\",";
}
myData = myData + "\"summaryAttributes\":\"di,tt\"}";
$.ajax({
url: "https://matrix.route.api.here.com/routing/7.2/calculatematrix.json",
type: "GET",
dataType: "jsonp",
jsonp: "jsoncallback",
data: myData,
success: function(data, status) {
console.debug(data);
var i;
for (i = 0; i < data.response.matrixEntry.length; i++) {
alert("Start" + i + ": Distance: " + data.response.matrixEntry[i].summary.distance + " Time: " + data.response.matrixEntry[i].summary.travelTime);
}
},
error: function(data) {
alert("error encountered trying to get mileage");
}
});
Could someone help me please with correct code and if possible where I'm going wrong.
make it like this:
var myData = {
app_code: "YOUR_APP_CODE",
app_id: "YOUR_APP_ID",
destination0: "52.5488,-3.4974",
mode: "fastest;car",
summaryAttributes: "di,tt"
};
// loop thru source locations
for (var i = 0; i < sourceLocations.length; i++)
myData["start" + i] = parseFloat(sourceLocations[i].lat) + "," + parseFloat(sourceLocations[i].lng);
$.ajax({
url: "https://matrix.route.api.here.com/routing/7.2/calculatematrix.json",
type: "GET",
data: myData,
success: function (data, status) {
console.debug(data);
var i;
for (i = 0; i < data.response.matrixEntry.length; i++) {
console.log("Start" + i + ": Distance: " + data.response.matrixEntry[i].summary.distance + " Time: " + data.response.matrixEntry[i].summary.travelTime);
}
},
error: function (data) {
alert("error encountered trying to get mileage");
}
});
I suggest you use Developer Tool (Press F12 for browsers) to check the request you sent.

How to remove all items from a kendoListBox

I have two kendo list boxes they exchange items between them. Basically an Items available and an Items selected pair.
I have Json service which controls what items are available via a Json array.
When the user selects a new filter I want both Kendo List Boxes to clear the items out before adding the new items from the server.
Currently it appends the new list from the server to the current list.
$(document).ready(function () {
$("#filterKeyWord").click(function () {
getResults($("#keywords"));
});
$("#availableReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
connectWith: "selectedReports",
dropSources: ["availableReports"],
toolbar: {
tools: ["transferTo", "transferFrom", "transferAllTo", "transferAllFrom", "remove"]
}
});
$("#selectedReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
dropSources: ["selectedReports"],
remove: function (e) {
setSelected(e, false);
},
add: function (e) {
setSelected(e, true);
}
});
var mydata = { ReportName: "", UserId: "" };
mydata.ReportName = "SomeName";
mydata.UserId = "SomeUser";
var crudService = "",
dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
update: {
url: crudService + "SaveReportList2",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "post",
},
filter: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read" && options.models) {
return JSON.stringify({ models: options.models });
}
if (operation === "read") {
return "request=" + JSON.stringify(mydata);
}
}
},
batch: true,
requestStart: function () {
kendo.ui.progress($(".demo-section"), true);
console.log("request start");
},
requestEnd: function () {
kendo.ui.progress($(".demo-section"), false);
console.log("request end");
},
error: function (e) {
console.log("Error" + e);
},
change: function (e) {
console.log("change" + this.data.length);
setDropDownBoxes(this);
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number" },
Selected: { type: "boolean" },
Name: { type: "string" },
Description: { type: "string" },
InternalId: { type: "string" }
}
}
}
});
$("#saveReportList").kendoButton({
click: function (e) {
dataSource.sync();
}
});
$("#getReportList").kendoButton({
click: function (e) {
mydata.ReportName = $("#keywords").val();
dataSource.read();
}
});
function setDropDownBoxes(obj) {
var data = obj.data();
var availableReports = $("#availableReports").data("kendoListBox");
var selectedReports = $("#selectedReports").data("kendoListBox");
var items = availableReports.dataItems();
for (var i = 0; i < data.length; i++) {
if (data[i].Selected) {
selectedReports.add(data[i]);
}
else {
availableReports.add(data[i]);
}
}
}
function setSelected(e, flag) {
var removedItems = e.dataItems;
for (var i = 0; i < removedItems.length; i++) {
console.log(flag + " " + removedItems[i].ID + " " + removedItems[i].Name + " " + removedItems[i].Selected);
var item = dataSource.get(removedItems[i].ID);
item.Selected = flag;
item.dirty = !item.dirty;
}
}
});
Not sure where in your exactly the clening should be performed, but, you can use both remove() and item() methods togheter to clear a listBox.
remove() method accepts a list of li elements, which is what items() returns, so it will remove the whole li collection from the list.
var listBox = $("#listBox").data("kendoListBox");
listBox.remove(listBox.items());
Demo

How to call Function in Jquery Datatable

I have these lines of code. I want to add function to some row. When clicked it runs another function. But It not recognise function declaration.How can I call function when clicked some row? and how can i send parameters to that function associated with that row.
$(document).ready(function() {
var restVul = function() {
alert("tik");
}
$.ajax({
url: "https://localhost:450/rest/products?pageNumber=1&pageCount=80",
type: "POST",
dataType: "json",
headers: {
'Content-Type': 'application/json'
},
traditional: true,
contentType: "application/json; charset=utf-8",
processData: false,
data: JSON.stringify(hostAddresses),
success: function(response) {
console.log(response);
for (var i = 0; i < response.length; i++) {
var trHTML = '';
for (var j = 0; j < response[i].Products.length; j++) {
trHTML += '<tr class="clickable-row" data-href="index.html"><td>' + response[i].IP + '</td><td onclick="function () {alert(); }">' + response[i].Products[j].Product + '</td><td>' + response[i].Products[j].CVECount + '</td></tr>';
}
$('#ProductsTableBody').append(trHTML);
}
$('.js-exportable').DataTable({
dom: 'Bfrtip',
responsive: true,
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
},
error: function(xhr) {
console.log("Hata Oluştu...");
}
})
Use following code in the row
columns: [
{"data": "xxx", "width": "10%","visible": false, "render": function (data, type, row, meta) { } },
]
Use following code inside the function to make a clickable link on column
if (type === 'display') {
return $('<a>')
.attr('href', ' ')
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}

Categories