cant get another column data from datatable using onclick function? - javascript

i have a problem in my script the ids and amount has a value while my Identitytype is null. im using onclick function to get all selected values based on specific column in datatable.
$(function () {
$('#PayableList').DataTable({
"columnDefs": [{ type: 'date', 'targets': [6] }],
"aaSorting": [[6, "desc"]],
"ajax": "#Url.Action("getpayablelist", "payable")",
"columns": [
{
"render": function (data, type, full, meta) {
return "<input type='checkbox' class='checkbox' onclick='add(" + full.Id + ", " + full.Amount + ", " + full.IdentityType + ", this.checked)'>"
}
},
{ "data": "Name" },
{ "data": "ReferenceNo" },
{ "data": "IdentityType" },
{ "data": "Amount" },
{ "data": "CustomerPayable" },
{ "data": "CreatedDate" }
]
});
});
var ids = [];
var amounts = [];
var identities = [];
function add(id, amount, IdentityType, isChecked) {
if (isChecked) {
ids.push(id);
amounts.push(amount);
identities.push(IdentityType);
}
else {
var i = ids.indexOf(id);
ids.splice(i, 1);
}
}
enter image description here

I don't see actual type of data rom the image, but I am assuming IdentityType is string and hence causing an issue. Update render method to:
"render": function (data, type, full, meta) {
return "<input type='checkbox' class='checkbox' onclick='add(" + full.Id + ", " + full.Amount + ", \"" + full.IdentityType + "\", this.checked)'>"
}
and it should work. You are not escaping string in the method due to which problem is happening.
Check this really bad practice code to see effect on your current code after change:
let full = {
Amount: 100.25,
Id: 1,
IdentityType: "SOMERANDOMTEXT"
};
document.body.innerHTML = "<input type='checkbox' class='checkbox' onclick='add(" + full.Id + ", " + full.Amount + ", \"" + full.IdentityType + "\", this.checked)' />";
function add(id, amount, identityType) {
console.log(`${id}, ${amount}, ${identityType}`);
}

Related

Unable to parse JSON filename object

I am unable to parse a JSON object (whatever.png) for some reason, I get [object%20Object] which is strange as I never have this issue, as its clearly simple to resolve or stringify and debug if in doubt.
My jQuery code:
$(function () {});
$.ajax({
url: '/shouts/get/ajax',
method: 'GET',
dataType: 'JSON',
success: function (res) {
res.forEach((element, i) => {
data = {
message: element['message'],
date: element['date'],
descr: element['descr'],
last_login: element['last_login'],
added: element['added'],
user: element['user'],
username: element['username'],
user_id: element['user_id'],
avatar: element['avatar'],
badges: element.badges
}
var result = XBBCODE.process({
text: data.message,
removeMisalignedTags: false,
addInLineBreaks: false
});
let allstring = '<div class="shoutbox-container"><span class="shoutDate" style="width:95px">' + jQuery.timeago(data.date) + ' <span style="color:#b3b3b3">ago</span><span id="user_badge_' + i + '"></span></span><span class="shoutUser"><a class="tooltip-shoutuser" title="' + data.username + '" href="/user/?id=' + data.user_id + '"><img src="' + data.avatar + '" class="shout-avatar" /></a></span><span class="shoutText">' + result.html + '</span></div><br>';
document.getElementById('shoutbox').innerHTML += allstring;
let badges = [];
data.badges.forEach(badge => {
badges.push('<img src="/images/avatars_gear/' + badge + '">').innerHTML += badges; // <--- Object bug
});
badges.forEach(badge => {
document.getElementById('user_badge_' + i).innerHTML += badge;
});
});
$('.shoutbox-container').filter(function () {
return $(this).children().length === 3;
}).filter(':odd').addClass('shoutbox_alt');
$('.shoutbox-container').each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
$('.tooltip-shoutuser').tooltipster({
animation: 'grow',
delay: 200,
theme: 'tooltipster-punk'
});
}
});
JSON output from PHP:
[
{
"badges": [],
"username": "tula966",
"message": "perk added for [url=/user/?id=39691]tula966[/url]",
"avatar": "images/avatars/0f885488eb90548b5b93899615c5b838d2300bdb_thumb.jpg",
"date": "2022-02-04 01:00:01",
"last_login": "2022-02-03 12:36:06",
"user_id": "39691"
},
{
"badges": [
{
"image": "star.png",
"descr": " Star Power"
},
{
"image": "toolbox.png",
"descr": "Worker"
}
],
"username": "Tminus4",
"message": "testing testing",
"avatar": "images/avatars/8cc11eb4cb12c3d7e00abfba341c30b32ced49be_thumb.jpg",
"date": "2022-02-04 01:00:00",
"last_login": "2022-02-03 10:52:08",
"user_id": "1"
}
]
badge is not pushing the PNG file names from the JSON response to the DIV. I cant figure this out. This same code structure works perfectly on 3 other areas using the same JSON structure and logic, in fact more complex in our Site Polls area without any issues.
I also attempted to force the object with json_encode($array, JSON_FORCE_OBJECT) on the PHP side, which breaks the JS - and I have never needed to utilize that before in any case.
However this seems to differ greatly in this case. Any help is appreciated.

jquery json showing undefined with html table parsing

I want to show below json data on html table.how can i show to html table when i try to show with below code its show mae undefined
[
{
"Key": "data",
"Value": [
[
{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [
{
"Key": "cursors",
"Value": [
{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}
]
}
]
Below is my Code and its show me undefined
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd'>" + item.ID + "</td>"
+ "<td class='prtoducttd'>" + item.Message + "</td>"
+ "</tr>";
$('#tblPost tbody').append(rows);
});
}
what is generic method to parse the json and show it to html table?
Out put
id message created_time
116312453556631_122404992947377 "My message" "2020-09-27T21:38:10+0000"
Check if item.Key == "data". If it is, loop through item.Value to get the values for that row.
var data = [{
"Key": "data",
"Value": [{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [{
"Key": "cursors",
"Value": [{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}]
}
];
$.each(data, function(i, item) {
if (item.Key == "data") {
let id, message, created;
$.each(item.Value, function(j, obj) {
switch (obj.Key) {
case 'id':
id = obj.Value;
break;
case 'message':
message = obj.Value;
break;
case 'created_time':
created = obj.Value;
break;
}
});
debugger;
let rows = "<tr>" +
"<td class='prtoducttd'>" + id + "</td>" +
"<td class='prtoducttd'>" + message + "</td>" +
"<td class='prtoducttd'>" + created + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblPost">
<thead>
<tr>
<th>ID</th>
<th>Message</th>
<th>Created Time</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Make sure you're getting the data correctly first
For example, at item[0] see if the scope chain shows object available. Use the debugger and console to look through the data structure to follow the scope chain. Then write a loop once you've got the item and i correctly.
$.each(data, function (i, item) {
for (i = 0; i < item.Value.length; i++) {
let rows = "<tr>" +
"<td class='prtoducttd'>" + item.Value[i][2].Value + "</td>" +
"<td class='prtoducttd'>" + item.Value[i][1].Value + "</td>" +
"<td class='prtoducttd'>" + formatDate(new Date(item.Value[i][0].Value)) + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});

Parse JSON dynamically and print key values on html with input checkbox and get a new JSON of selected keys

I am trying to parse an unknown JSON whose format could be anything. So, I dont know the keys to access it. I want to access every key in JSON and print out all keys and values on screen using HTML. So I made a recursive function to access every key in JSON and used a variable name html to print the keys.
here`s the code:
JSON String:
{
"FetchDetails": {
"TransactionDetails": {
"ServiceName": "Airtel Mobile Bill Postpaid",
"officeID": "209",
"BillAmount": "931.00",
"ConsumerName": "Chetan Kumar Yadav",
"consumerKeysValues": "9352423664",
"partPaymentAllow": "1",
"partPaymentType": "Both",
"lookUpId": "6163298",
"officeCodeValue": "RATNC011"
},
"BillDetails": [{
"LableName": "Amount Before Due Date",
"LableValue": "931.00"
}, {
"LableName": "Due Date",
"LableValue": "NA"
}, {
"LableName": "Mobile Number",
"LableValue": "9352423664"
}, {
"LableName": "Amount After Due Date",
"LableValue": "931.00"
}, {
"LableName": "Bill Date",
"LableValue": "NA"
}, {
"LableName": "Consumer Name",
"LableValue": "Chetan Kumar Yadav"
}, {
"LableName": "Bill Cycle",
"LableValue": "NA"
}, {
"LableName": "Bill Number",
"LableValue": "NA"
}, {
"LableName": "Account Number",
"LableValue": "1116231291"
}]
}
}
Heres the code to access every key in Parsed JSON
function scan(info) {
var sub_root = [];
if (info instanceof Object) {
for (k in info) {
if (info.hasOwnProperty(k)) {
console.log('scanning property ' + k);
if (info[k] instanceof Object) {
me += "<div class='root'> <div class='sub_root'> <input class='node' name='sub_root[" + k + "]' value='" + k + "' type='checkbox' />" + k;
console.log(k);
counter++;
scan(info[k]);
me += "</div>";
me += "</div>";
} else {
me += "<div class='json_check' ><input class='node' name='sub_root[" + y + "] [" + k + "]' value='" + k + "' type='checkbox' />" + k + ": " + info[k] + " </div>";
scan(info[k]);
counter++;
}
}
}
} else {
console.log('found value : ' + info);
}
}
After this, I am able to access every key in JSON and printed every node in a nested form with checkboxes in front of them to select any node/key.
Here`s the screenshot:
[PROBLEM to be solved]
Now at the bottom, I have a submit button, when I click on it I want to form a JSON of checked values with their parent nodes. So like if I check a key with a value, I should get its parent keys along with it.
For example: I have selected ServiceName and officeID in TransactionDetails, and some array values in BillDetails, so I should get something like this
{
"FetchDetails": {
"TransactionDetails": {
"ServiceName": "Airtel Mobile Bill Postpaid",
"officeID": "209"
},
"BillDetails": [{
"LableName": "Amount Before Due Date",
"LableValue": "931.00"
}, {
"LableName": "Due Date",
"LableValue": "NA"
}, {
"LableName": "Account Number",
"LableValue": "1116231291"
}]
}
}
[EDITED]
To get this JSON format and traverse through HTML objects I am writing this code:
$('#btn_createservice').on('click', function() {
var solid = '{';
var input = $('input').is(':checked');
if(input){
input = $('input');
}
$('.node:checked').each(function(index) {
var parentEls = $(this).closest(input)
.map(function() {
solid += this.value;
return this.value;
})
.get()
.join( ", " );
console.log(parentEls);
});
solid += '}';
$( ".submit_json" ).html(solid);
});
You need to use .parents(), not .closest() so you get all the containing elements.
Then create containing properties with those names when necessary.
$("#btn_createservice").on("click", function() {
var svc_obj = {};
$(".node:checked").each(function() {
var cur_obj = svc_obj;
$(this).parents(".node").map(function () {
return this.value;
}).get().reverse().forEach(function(name) {
if (!cur_obj[name]) { // create property if it doesn't already exist
cur_obj[name] = {};
}
cur_obj = cur_obj[name]; // use this for next iteration;
});
var thisname = this.name.match(/\[([^[])+\]$/)[1]; // Get property name from name="sub_root[...]"
cur_obj[thisname] = this.value;
});
$(".submit_json").html(JSON.stringify(svc_obj));
})
You need to fix the HTML you're creating so that the checkboxes have value='" + info[k] "'.

"decodeURIComponent" items in JSON List

I want to parse all the items in the JSON list and using the function decode, remove the HTML formatted spaces, %20 and the like.
See snippet below
My goals:
I want to change Andy%2EPeters to "Andy Peters"
I dont want to have to refer to each item as "this.product_model" using the key name.
$(document).ready(function() {
$('.btn').click(function() {
$(ray).each(function(index) {
console.log("Item BEFORE Decode : " + index + ": " + $(this).text() + ": " + this.product_model);
this.index = decodeString(this.item);
console.log("Item AFTER Decode : " + index + ": " + $(this).text() + ": " + this.product_model);
});
});
});
function decodeString(a) {
if (typeof a != 'undefined') {
return decodeURIComponent(a);
} else {
return '';
}
}
var ray = [{
"product_id": "1",
"product_model": "Andy%2EPeters",
}, {
"product_id": "2",
"product_model": "Tom%2EHanks",
}, {
"product_id": "1",
"product_model": "HFJ5G1.5",
}, ];
//console setup
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function(text) {
$("#console-log").append($(consoleLine).html(text));
}
};
.console-line {
font-family: console;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="btn" type="button" id="btn" value="Go!">
<div id="console-log"></div>
Thanks
$(document).ready(function() {
$('.btn').click(function() {
var data = decodeURIComponent(JSON.stringify(ray).replace(/(%2E)/ig, "%20"));
ray = JSON.parse(data);
$(ray).each(function(){
console.log(this.product_model);
})
});
});
var ray = [{
"product_id": "1",
"product_model": "Andy%2EPeters"
}, {
"product_id": "2",
"product_model": "Tom%2EHanks"
}, {
"product_id": "1",
"product_model": "HFJ5G1.5"
} ];
//console setup
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function(text) {
$("#console-log").append($(consoleLine).html(text));
}
};
.console-line {
font-family: console;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="btn" type="button" id="btn" value="Go!">
<div id="console-log"></div>
This uses the JSON object's native stringify to parse the object to a JSON string. Before decoding is done replace all the %2E with %20 and finally decode it all together. Then parse it back to a JavaScript object.
I don't know if this is for demonstration purposes only, but generally speaking: overwriting the console is a bad idea.

json obj with array

How can i loop the contacts inside my json object using javascript?
{
"success": 1,
"contacts": [
{
"cName": "testing",
"cmail": "testMail",
"ctlf": "testPhone"
},
{
"cName": "testing",
"cmail": "testMail",
"ctlf": "testPhone"
}
],
"fName": "Actura",
"fAdr": "langdyssen 5, 8200 Aarhus N",
"date": "14-9-2019"
}
I've tried using the code below, but it only displayed 0 and 1 at the console
$.getJSON("./ajax/get.php", {
type: "printer",
placement: "firm",
id: id
}).done(function (data) {
if (data.success == 1) {
//$('table#printerInfo').append("<tr><td>Printer ID</td><td>" + data.id + "</td></tr>").append("<tr><td>M&aeligrke</td><td>" + data.brand + "</td></tr>").append("<tr><td>Model</td><td>" + data.model + "</td></tr>").append("<tr><td>Farve</td><td>" + data.color + "</td></tr>");
$('table td#firmName').append('<span class="glyphicon glyphicon-home"></span> ' + data.fName);
$('table td#firmAdr').append('<span class="glyphicon glyphicon-globe"></span> ' + data.fAdr);
$('table td#firmDate').append('<span class="glyphicon glyphicon-calendar"></span> ' + data.date);
for (var contact in data.contacts) {
console.log(contact);
}
console.log(data);
toolTip();
}
else {
alert("Der er sket en fejl: " + data.error);
}
});
Replaced data with test data, and due to 'too much code' ill be adding some ekstra text since i cant delete the question due to answers
Use code below instead:
for (var i in data.contacts) {
console.log(data.contacts[i]);
}

Categories

Resources