REST API call not populating table with array contents - javascript

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>";
}```

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.

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] "'.

Populate SELECT with data from JSON file using ajax

I am new with using JSON file for web development and I got interest with it due to it usefulness and power in terms of data storage. Right now, I want to use JSON file via path instead of adding the JSON into the same page because it make the page full of JSON data. Yesterday I have the following codes but only adding the JSON file into the same page not into separate one. How can I use JSON file path instead of adding JSON into the same page?
HTML
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="form-group">
<label for="supplier_bank_name">Bank Name</label>
<select class="form-control selectpicker" data-live-search="true" id="supplier_bank_name" name="supplier_bank_name"></select>
</div>
</div>
PREVIOUS CODE
This code will work well but JSON only in the same page.
var allbanks = {
banks:[
{
"index": 0,
"bankname": "1st Source Bank",
"location": "USA",
"website": "www.1stsource.com"
},
{
"index": 1,
"bankname": "1st Summit Bank",
"location": "North America",
"website": "www.1stsummit.com"
},
{
"index": 2,
"bankname": "A.J. Smith Federal Savings Bank",
"location": "USA",
"website": "www.ajsmithbank.com"
}
]
};
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});
SCRIPT TODAY
Not working and looking for solution
var allbanks = (function () {
var allbanks = null;
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
allbanks = data;
}
});
return allbanks;
})();
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});
JSON
{
"banks": [
{
"index": 0,
"bankname": "1st Source Bank",
"location": "USA",
"website": "www.1stsource.com"
},
{
"index": 1,
"bankname": "1st Summit Bank",
"location": "North America",
"website": "www.1stsummit.com"
},
{
"index": 2,
"bankname": "A.J. Smith Federal Savings Bank",
"location": "USA",
"website": "www.ajsmithbank.com"
}
]
}
Since $.ajax is an asynchronous function, the code within allbanks will execute in this order:
Assign allbanks to null
Make ajax request
Return allbanks, which is still set to null because the ajax request has not returned yet.
Receive data and assign that to allbanks (This will not return out of the function and will not be set to the allbanks variable on the first line)
To fix this, you should use the data within the success portion of the ajax request.
function createSelectItems(data) {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < data.banks.length; i++) {
listItems += "<option data-tokens='" + data.banks[i].bankname + "' value='" + data.banks[i].bankname + "'>" + data.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
}
$(document).ready(function () {
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
createSelectItems(data);
}
});
});
EDIT
See comments below:
allbank_connect.js
// Code goes here
var allbanks = (function () {
var allbanks = null;
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
allbanks = data;
}
});
return allbanks;
})();
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});

Get cascading data from form into JSON object

I am trying to build a 'form builder' where you can add sub-fields to fields, and sub-fields to those sub-fields, etc. I have that part working and the output html I have pasted here on pastebin
Which looks like:
I need to get the data into this format:
var form_structure = {
iGA2cXN3XXdmr1F: {
title: "Field 1",
help: "",
placeholder: "",
type: "multi-select",
options: {"123QWE": "Opt 1", "ASDZXC": "Opt 2", "ASDQWE": "Opt 3"},
subfields: {
m8r32skADKsQwNt: {
title: "Field 1.1",
help: "",
placeholder: "",
type: "text",
options: []
},
m8r32skADKsQwNt: {
title: "Field 1.2",
help: "",
placeholder: "",
type: "text",
options: []
},
m8r32skADKsQwNt: {
title: "Field 1.3",
help: "",
placeholder: "",
type: "text",
options: [],
subfields: {
m8r32skADKsQwNt: {
title: "Field 1.3.1",
help: "",
placeholder: "",
type: "text",
options: []
}
}
}
}
},
aBvXXN3XXdmr1F: {
title: "Field 2",
help: "",
placeholder: "",
type: "multi-select",
options: {"123QWE": "Opt 1", "ASDZXC": "Opt 2", "ASDQWE": "Opt 3"},
subfields: {
m8r32skADKsQwNt: {
title: "Field 2.1",
help: "",
placeholder: "",
type: "text",
options: []
}
}
}
};
I have tried (sorry for the bad formatting):
function buildRequestStringData(form) {
var select = form.find('select'),
input = form.find('input'),
options_arr = [],
obj = {},
requestString = '{';
for (var i = 0; i < select.length; i++) {
if(typeof $(select[i]).data('parentid') != 'undefined') {
// has parent
if($(select[i]).data('parentid') != $(select[i]).data('mainid')) {
requestString += '"' + $(input[i]).data('mainid') + '":"' + JSON.stringify(buildRequestStringData()) + '",';
}
} else {
// does not have parent
requestString += '"' + $(select[i]).attr('name') + '": "' +$(select[i]).val() + '",';
}
}
// if (select.length > 0) {
// requestString = requestString.substring(0, requestString.length - 1);
// }
for (var i = 0; i < input.length; i++) {
// if ($(input[i]).attr('type') !== 'checkbox') {
requestString += '"' + $(input[i]).attr('name') + '":"' + $(input[i]).val() + '",';
// } else {
// if ($(input[i]).attr('checked')) {
// requestString += '"' + $(input[i]).attr('name') +'":"' + $(input[i]).val() +'",';
// }
// }
}
if (input.length > 0) {
requestString = requestString.substring(0, requestString.length - 1);
}
requestString += '}]';
return requestString;
}
The best way I have been able to be close to this is on this fiddle - but that only allows me to put the id down, and does not format it into the format I need.
What is the best way to do this?
I think you're on the right track. See if you can nest your HTML in the same structure you want for your JSON, then when harvesting the details for each item, walk up the DOM tree grabbing each parent's id until you get to the form, and then create / append to the nested JSON object the data you find. If this isn't descriptive enough, I'll mod the answer to include html and js examples.

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