How to display string having XML data - javascript

My JSON data is:
[
{
"serviceName":"test",
"requestXML":"<soapenvelope><uname>testuser</uname></soapenvelope>"
},
{
"serviceName":"test2",
"requestXML":"<soapenvelope><uname>testuser2</uname></soapenvelope>"
}
]
jQuery code to call to backend which returns this JSON data
var postRequest = $.post(url);
postRequest.done(function( data ) {
$('#tableid').dataTable( {
"processing": true,
destroy: true,
"aaData": data,
"aoColumns": [
{ "data": "serviceName" },
{ "data": "requestXML" },
]
});
});
Now when it is shown on the screen as jQuery DataTable, I wanted the entire XML to be printed as it. But it just prints testuser instead of the whole XML.
Could anyone please help me with this as what is going wrong?
I have verified my JSON data is going correctly.

SOLUTION
You can use $('<div/>').text(data).html() trick to encode HTML entities.
For example:
$('#tableid').dataTable({
"processing": true,
"destroy": true,
"data": data,
"columns": [
{
"data": "serviceName"
},
{
"data": "requestXML",
"render": function(data, type, full, meta){
return $('<div/>').text(data).html();
}
}
]
});
DEMO
See this jsFiddle for code and demonstration.

Your server should take care of the response what it is sending. instead of sending
[
{"serviceName":"test","requestXML":"<soapenvelope><uname>testuser</uname></soapenvelope>"},
{"serviceName":"test2","requestXML":"<soapenvelope><uname>testuser2</uname></soapenvelope>"}
]
it should send something like below
[
{"serviceName":"test","requestXML":"<soapenvelope><uname>testuser</uname></soapenvelope>"},
{"serviceName":"test2","requestXML":"<soapenvelope><uname>testuser2</uname></soapenvelope>"}
]
If that is not possible ( you don't control the server ) then the following link should help
Escape markup in JSON-driven jQuery datatable?

First of all you will need XML escaping function (taken from here):
var XML_CHAR_MAP = {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
"'": '&apos;'
}
function escapeXml (s) {
return s.replace(/[<>&"']/g, function (ch) {
return XML_CHAR_MAP[ch]
})
}
Then you can render cell content using it:
{
data: "requestXML",
render: function(data, method, object, pos) {
return '<pre>' + escapeXml(data) + '</pre>'
}
}
Now your XML should be visible. Remove pre tags, if not required.

Related

Datatable send current page number

I've been try to send current page number to server by overwrite a variable called pgno
here is my code :
function fill_datatable(status='',pgno='')
{
var pgno = 0;
table = $('.tb_scoin_available').DataTable({
"processing": true,
"serverSide": true,
"ordering" : false,
"infoCallback": function( settings, start, end, max, total, pre ) {
var api = this.api();
var pageInfo = api.page.info();
pgno = pageInfo.page+1;
return pgno;
},
"ajax":{
"url": base_url+'/adminPath/management_scoin/ajaxGetScoinAvailable',
"type": "POST",
"data":{ _token: csrf_token, status : status,pgno : pgno}
},
"columnDefs": [ { orderable: false} ],
"columns": [
{ "data": "no" },
{ "data": "created_at" },
{ "data": "serial_scoin" },
{ "data": "unit_scoin" },
{ "data": "unit_scoin_desc" },
{ "data": "unit_scoin_sc" },
{ "data": "unit_scoin_idr" },
],
});
}
when I try to alert on infoCallback :
alert(pgno) the variable already overwrited, but when I try to dump the request on backend the pgno POST give me null result like this :
Anyone can help me out ?
You can get the table page with the page() function, no need for the whole "page.info". It's better explained in Datatable's API: https://datatables.net/reference/api/page()
The method you're trying to access is only to get the information, not to set it. That is probably why it isn't working. Check their docs for better understanding of their API: https://datatables.net/reference/api/page.info()
EDIT:
You can get the current page through a simple calculation. Since you're using serverSide processing, you already have start and length. You just need to do start/length + 1 and you will get the current page number.

generate javascript code with php

I would like to dynamically generate the columns definition on a Datatable. The columns definitions are:
"columns": [
{ "data": "id", "orderable": false },
{ "data": "code" },
{ "data": "name" },
{ "data": "created", "render":
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
},
{ "data": "modified", "render":
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
}]
I tried generating the javascript code using an array of php objects and then json_encode it, like the following:
$formatted_cols = [];
foreach ($cols as $idx => $col){
$temp = [];
$temp['data'] = $col;
if(in_array($col, array('id', 'actions'))){
$temp['orderable'] = 'false';
}
if(in_array($col, array('created', 'modified'))){
$temp['render'] = "
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
";
}
$formatted_cols[] = $temp;
}
And then I do the following in the place where the code would normally appear:
echo json_encode($formatted_cols);
But the code came out like this:
[
{
"data": "id",
"orderable": "false"
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "created",
"render": "\r\n function (data) {\r\n var date
= new Date(data);\r\n \r\n return
date.toLocaleString();\r\n }\r\n "
},
{
"data": "modified",
"render": "\r\n function (data) {\r\n var date
= new Date(data);\r\n \r\n return date.toLocaleString();\r\n }\r\n "
}
]
As you can see, with a bunch of \r\n and stuff. Anybody can help me get the desired output please?
Thanks in advance for any help
UPDATE
I removed the line breaks but still the functions are inside double quotes
{
"data": "modified",
"render": "function (data) {var date = new Date(data);return
date.toLocaleString();}"
}
How do I remove those quotes?
Try using nl2br(). It'll take away all those \r and \n
http://php.net/manual/es/function.nl2br.php
The \r\n "stuff" represents a carriage-return + linefeed combination, in other words a line break.
You're going to get these in the JSON data if you're trying to encode multi-line strings. JSON itself does not support multi-line strings without them like PHP does.
Remove your newlines, like this:
{ "data": "created", "render": "function (data) { var date = new Date(data); return date.toLocaleString(); }" },
But you'll still be left with a string, which isn't the sort of thing you should work with, even though you can convert it to a function in JS. It's pretty ugly. Even if it worked, it's not great to generate JS in PHP - try to find another method if you can. Let PHP serve only the data, and have JS integrate functionality into it, if possible.

Send jquery datatable column value to Javascript Function (Asp.Net MVC)

I am binding data to jquery datatable in asp.net mvc, i have an anchor tag in one of the columns of the grid where i am accessing / reading row data and sending that data to a javascript function. The problem which i am facing is, i am able read and send row values to the function which are numbers for example ProductID="1" or CategoryID="3" , but if i try to send ProductName="Chai" to the javscript function i get an error in the console, and if i remove the parameter "ProductName" everything works fine and the javascript function also gets triggered.
Following the console error:
"Index:1 Uncaught ReferenceError: Chai is not defined
at HTMLAnchorElement.onclick (Index:1)"
Following is my Code:
var BindDataTable = function (response) {
$("#tbProduct").DataTable({
"aaData": response,
"aoColumns": [
{ "mData": "ProductID" },
{ "mData": "ProductName" },
{ "mData": "SupplierID" },
{ "mData": "SupplierName" },
{ "mData": "SupplierCountry" },
{ "mData": "CategoryID" },
{ "mData": "CategoryName" },
{ "mData": "QuantityPerUnit" },
{ "mData": "UnitPrice" },
{
"render": function (data, type, full, meta) {
return '<i class="glyphicon glyphicon-pencil"></i>'
}
}
],
"columnDefs": [
{
"targets": [2],
"visible": false,
"searchable": false
},
{
"targets": [5],
"visible": false,
"searchable": false
}
],
"aaSorting": []
});
}
var EditProduct = function (ProductID, SuppID, CatID,PrdName) {
var url = "/Product/EditProduct?ProductID=" + ProductID + "&SuppID=" + SuppID + "&CatID=" + CatID;
$("#myModalBodyDiv1").load(url, function () {
$("#myModal1").modal("show");
})
}
Error:
My suggestion is that instead of playing around with that much string concatenations, what you can do is pass single object to your function and then use the required fields which needs to be passed as ajax call:
"render": function (data, type, full, meta) {
return '<i class="glyphicon glyphicon-pencil"></i>'
}
and in your js function use it :
var EditProduct = function (product) {
var url = "/Product/EditProduct?ProductID=" + product.ProductID+ "&SuppID=" + product.SupplierID + "&CatID=" + productCategoryID + "&ProdName=" + product.Prooductname ;
You can use the following approach in for passing string arguments to a JavaScript function:
<a onclick="javaScriptFunction(#p.ID, '#p.FileName');">#p.FileName</a>
function javaScriptFunction(id, fileName) {
...
}

Datatables 1.10 / Columns / download_link shows but without expected data but with a link

I have a table that I have successfully created with Datatables. I am trying to show data with a hyperlink. When I use columnDefs, the columns performs as expected and shows a bit of data (as expected) with a hyperlink. Here is the code:
// below works as expected. It shows the ID which is the data
// in a hyperlink
"columnDefs": [{
"targets": 0,
"data": "download_link",
"render": function(data, type, full, meta) {
return '' + data + '';
}
}]
On the otherhand, I am trying to do the same thing using "columns" and it does not produce a similar result. The below example shows "undefined" but it does produce a hyperlink to undefined. Here is the code snipplet:
"ajax": "json_get_countries",
// country column does not work as expected. It shows "undefined" and a hyperlink
// connected to the word underdefined
"columns": [{
"data": "country_id",
"searchable": false
},
{
"data": "country",
"data": "download_link",
"render": function(data, type, full, meta) {
return '' + data + '';
}
},
{
"data": "country_enabled"
}
]
I have tried to remove this code:
"render": function(data, type, full, meta) {
return '' + data + '';
and it does work. It does show the data just without the hyperlink.
I have tried to change +data+ to +country+ but that also did not work.
Any help appreciated.

Post row datas from DataTable to an Ajax Form

I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)

Categories