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ærke</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]);
}
Related
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.
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}`);
}
I have a query that fires off when a user goes to a page, which returns the on-shift points of contact for escalations. The issue I'm experiencing is that nothing is being populated into the table I have designated for these POCs. I've added my code below, including the HTML element this should be populating into, but I get no errors thrown back in the console, and I know that there is data that should populate into this as I've run the Ajax query and looked through the XML results and I can see entries that should show. I have another call on the same page that contacts another list to retrieve on-going critical incidents and that one works without any issues, so I've convinced myself that it's the .innerHTML part that's causing the issue, as the initial .innerHTML = ""; command is clearing the Placeholder text, however nothing else is being completed.
var filManager = [];
var mancontact = document.getElementById("managercontact");
function getContacts() {
$.ajax({
url: ".../_api/web/lists/getbytitle('On Shift Contacts')/items?$filter=Status eq 'In'&$select=Title,Id,Role,Status,Number,Brand",
type: "GET",
headers: {
"accept": "application/json;odata=verbose"
},
success: function(data) {
filManager = data.d.results;
filManager = filManager.filter(function(item) {
return item.Role == "Incident Manager";
});
if (filManager === undefined || filManager == 0) {
mancontact.innerHTML = "<tr><td style='font-family:Calibri'><center>There are currently no on-shift Managers</center></td></tr>";
} else {
mancontact.innerHTML = "";
mancontact += "<tr style='font-family:Calibri;font-size:14pt;text-align:center'><td colspan='3'>Manager On-Shift</td></tr><tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>Name</td><td>Contact Number</td><td>Location</td></tr>";
for (var obj in filManager) {
mancontact.innerHTML += "<tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>" + filManager[obj].Title + "</td><td>" + filManager[obj].Number + "</td><td>" + filManager[obj].Brand + "</td></tr>";
}
}
}
});
}
<center>
<table id="managercontact">
<tr>
<td>Placeholder</td>
</tr>
</table>
</center>
example array output from the call:
filManager = [
{ID:"1", Title: "Person1", Status: "In", Role: "Incident Controller", Brand: "Consumer", Number: "01234 567 890"},
{ID:"2", Title: "Person2", Status: "In", Role: "Incident Manager", Brand: "Consumer", Number: "01234 567 890"},
{ID:"3", Title: "Person3", Status: "Off", Role: "Incident Manager", Brand: "Business", Number: "01234 567 890"},
{ID:"4", Title: "Person4", Status: "Off", Role: "Incident Controller", Brand: "Business", Number: "01234 567 890"},];
I managed to find a missing innerHTML in the if statement. Adding in the below code instead of the if statement above has resolved this issue for me.
mancontact.innerHTML = "<tr><td style='font-family:Calibri'><center>There are currently no on-shift Managers</center></td></tr>";
} else {
mancontact.innerHTML = "";
mancontact.innerHTML += "<tr style='font-family:Calibri;font-size:14pt;text-align:center'><td colspan='3'>Manager On-Shift</td></tr><tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>Name</td><td>Contact Number</td><td>Location</td></tr>";
for(var obj in filManager){
mancontact.innerHTML += "<tr style='font-family:Calibri;font-size:12pt;text-align:center'><td>" + filManager[obj].Title + "</td><td>" + filManager[obj].Number + "</td><td>" + filManager[obj].Brand + "</td></tr>";
}```
I've JSON in the following format that I'm trying to insert into outlook/email client's body using
location.href = "mailto:" + "email#domain.com" + "?subject=" + "Notes" + "&body=" + JSON.stringify(data, null, 4);
Giving 4 spaces JSON.stringify(data, null, 4)
[
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
]
I want to output as
<b>article_0_page_0</b>\n\r
Note 1
<b>article_0_page_1</b>\n\r
Note 2
Any regular expression solution please.
Edit: My attempt
var str = "";
for(var i=0; i<data.length; i++) {
str += "<strong>" + data[i].page + "</strong><br>" + data[i].note + "<br><br>";
}
I think the above answer is ok if you have a flat structure.
If you want a more holistic approach for email specifically, I have found this to work really well.
const data = {...}
JSON.stringify( data, null, ' ' ).split( '\n' ).join( '<br>' );
This will convert something like this
const json = {
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
Into something like this
{<br> "status": "ok",<br> "config": {<br>  "gotIt": "yes",<br>  "transform": [<br>   null<br>  ]<br> }<br>}
Email clients will render this as the following
{
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
This is done by using the additional parameters in JSON.stringify which I don't see used very often if you want to read more about these parameters here is the link for them.
Here ya go
var json = [
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
];
var out = "";
for (var key in json) {
if (json.hasOwnProperty(key)) {
out += "<b>"+json[key].page+"</b>\r\n"+json[key].note+"\r\n\r\n";
}
}
console.log(out);
Example Here: https://jsfiddle.net/q5r4gdcn/1/
This is what I used to convert basic JSON to "readable" for email:
let json = {
"key": "asdas",
"query": "",
"hints": {
"nested1": "blahblah"
}
}
let prettyJSON = JSON.stringify(json, null, ' ')
.split('\n')
.join('<br> ')
.split('<br> }').join('<br>}')
document.body.innerHTML += `<div>${prettyJSON}</div>`
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.