jQuery AJAX set data multiple or single data to each field - json

I have AJAX/JSON operation that calls a PHP endpoint.
I'm getting data from database and need to set it to each field.
Here is the Ajax code:
$.ajax(
{
url: "loadEquipmentDetails",
type: "POST",
data:
{
equipmentID: equipmentIDValue
},
success: function(jsonStr)
{
var data = JSON.parse(jsonStr);
var item1Len = data.item1Name.length;
$('#equipmentIDFilter').val(data.equipmentID);
$('#equipmentNameFilter').val(data.equipmentName);
for(var i=0; i<item1Len; i++)
{
var item1Name = data[i].item1Name;
alert(item1Name);
var newOption = $('<option>baba</option>');
$('#item1IDFilter').append(newOption);
}
}
});
As you can see on above code, for this:
$('#equipmentIDFilter').val(data.equipmentID);
$('#equipmentNameFilter').val(data.equipmentName);
Working good, the value can be set to that ID.
But why the value is not show on below:
var newOption = $('<option>baba</option>');
$('#item1IDFilter').append(newOption);
I try to alert it alert(item1Name) but there is no result/pop up.
Response result:

There is a problem with the logic of your loop.
var item1Len = data.item1Name.length;
later on you have
for(var i=0; i<item1Len; i++)
{
var item1Name = data[i].item1Name;
alert(item1Name);
var newOption = $('<option>baba</option>');
$('#item1IDFilter').append(newOption);
}
which assumes that data is an array, and each item has a key item1Name
I could only make assumptions of how your data looks like but I imagine it would have to be something like
for(var i=0, iMax = data.options.length; i<iMax; i++)
{
if(data.options[i].hasOwnProperty('item1Name')) {
var item1Name = data.options[i].item1Name;
var newOption = $('<option>${item1Name}</option>');
$('#item1IDFilter').append(newOption);
}
}
UPDATE: after the json was added to the question
if (data.hasOwnProperty('item1Name')) {
for (var i = 0, iMax = data.item1Name.length; i < iMax; i++) {
var item1Name = data.item1Name[i];
var newOption = $('<option>${item1Name}</option>');
$('#item1IDFilter').append(newOption);
}
}

Related

renameCustomField() Change the Label Field Name

SVP i'm newsbe in Appsscript with API PEOPLE
This script don't work : I want to rename "CKD EPI" by "CKD EPI / CROKOFF / CREAT"
Can you tell me what's wrong ?
function renameCustomField() {
var debug = true;
var group = People.PeopleApi.getContactGroups().get("Mygroup").execute();
var oldFieldName = "CKD EPI";
var newFieldName = "CKD EPI / CROKOFF / CREAT";
for (var i = 0; i < group.members.length; i++) {
var contact = group.members[i];
var fields = contact.userDefined;
for (var j = 0; j < fields.length; j++) {
if (fields[j].key === oldFieldName) {
fields[j].key = newFieldName;
if (debug) {
console.log("Renaming field for contact: " + contact.names[0].displayName);
}
}
}
var updateContact = {
resourceName: contact.resourceName,
updatePersonFields: "userDefined",
userDefined: fields
}
People.PeopleApi.updateContact(updateContact).execute();
}
}

Cannot append option for select form

I want to load option data from a Sheet and append to the select element, but I cannot set the global variable
var select_values = [];
google.script.run.withSuccessHandler(loadOpt).loadData("Test");
function loadOpt(data_arrar) {
const arrayColumn = (arr, n) => arr.map(x => x[n]);
select_values = arrayColumn(data_arrar, 1);
}
var opt = document.getElementById("select_opts");
for (i = 0; i < select_values.length; i++) {
let option = document.createElement("option");
option.value = i;
option.text = select_values[i];
opt.appendChild(option);
}
The result is nothing appended to [select_opts].
I'm update the code.gs.
var TestSheets = SpreadsheetApp.openById("XXX");
function doGet(e) {
if (!e.parameter.page) {
// When no specific page requested, return "home page"
return HtmlService.createTemplateFromFile('Home').evaluate();
}
// else, use page parameter to pick an html file from the script
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
}
function loadData(Sheetname) {
var sheet = TestSheets.getSheetByName(Sheetname);
var rows = sheet.getRange("A1").getValue();
var Columns = sheet.getRange("B1").getValue();
var data_return = [];
for (var i = 0; i <= rows; i++) {
data_return[i] = [];
for (var j = 0; j <= Columns - 1; j++) {
data_return[i][j] = sheet.getRange(i + 2, j + 1).getValue();
}
}
return data_return;
}
Note that function loadData works well & has been tested.
The problem is that Javascript code outside of functions will be called on loading of the HTML document
It will not be reevaluated after running code in functions
If you want your loop to run after function loadData(Sheetname) - you need to put the loop into another function that is called after the execution of function loadData(Sheetname)
Sample:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var select_values = [];
google.script.run.withSuccessHandler(loadOpt).loadData("Test");
function loadOpt(data_arrar) {
const arrayColumn = (arr, n) => arr.map(x => x[n]);
select_values = arrayColumn(data_arrar, 1);
console.log(" select_values: " + select_values);
callLater();
}
console.log(" select_values in call outside: " + select_values);
function callLater(){
console.log(" select_values in callLater: " + select_values);
var opt = document.getElementById("select_opts");
for (i = 0; i < select_values.length; i++) {
let option = document.createElement("option");
option.value = i;
option.text = select_values[i];
opt.appendChild(option);
}
}
</script>
</body>
</html>

Removing duplicates while loading a combo in HTML using a txt file

Below is my code to load the combo using a txt file:
$("#Combo1").change(function() {
$('#Combo2').empty();
$.ajax({
url: 'File.txt',
type: 'get',
success: function(txt){
var value = [];
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++)
{
var tmpData = txtArray[i].split(',');
if (!value[tmpData[1]])
{
value.push([tmpData[1]]);
value[tmpData[1]] = true;
}
}
$('#Combo2').empty();
$.each(value, function(i, p) {
$('#Combo2').append($('<option></option>').val(p).html(p));
});
}
})
});
$("#Combo1").trigger("change");
Here on change of Combo1, this will be called. The Ajax is used to read the content of File.txt File.txt has a "," seperated two columns, out of which I am willing to print coulmn2. Given below are the contents of File.TXT.
A,31JAN
B,25JAN
C,31JAN
D,6JAN
E,6JAN
I was to load the above dates in Combo2. With the above code, I am able to ignore 31JAN. But 6JAN is getting repeated. In short, the value which is given at the last row gets repeated. Rest is fine.
Try this:
var txt="A,31JAN\nB,25JAN\nC,31JAN\nD,6JAN\nE,6JAN";
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++)
txtArray[i] = txtArray[i].split(",").pop();
var value = txtArray.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]);
console.log(value); //returns array
Also, give this a read: https://stackoverflow.com/a/9229821/9920079 :)

Angular 2 - Parsing Excel worksheet to Json

I have an Excel file with the following content:
Inside my component.ts, I extract the Excel's content as follow:
var testUrl= "excel.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i){
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
var jsonOut = JSON.stringify(json);
console.log("test"+jsonOut);
}
oReq.onerror = function(e) {
console.log(e);
}
oReq.send();
XLSX.utils.sheet_to_json will format JSON as follow:
However, I would like the JSON to be as follow:
Most probably I would need to manually create the JSON, but can anyone help me point to the direction on how I can accomplish this?
In your case we need to modify the JSON data by looping over XLSX.utils.sheet_to_json JSON object:
// This object will contain the data in the format we want
var finalObj = { "object": []};
// Variables to track where to insert the data
var locIndex, firstCondIndex, secondCondIndex,
lockey, firstCondKey, secondCondkey;
// We need to initialize all indexes to -1 so that on first time we can get 0, as arrays start with 0 in javascript
locIndex = -1;
// here obj is XLSX.utils.sheet_to_json
obj.object.map((value, index) => {
// we don't want to consider name of columns which is first element of array
if(!index) return;
// Go inside only if not null
if(value[0]) {
// For Location
finalObj.object.push(createObj(value[0]));
locIndex++;
// We also need to store key names to push it's children
lockey = value[0];
firstCondIndex = -1;
}
if(value[1]) {
// For First Condition
finalObj.object[locIndex][lockey].push(createObj(value[1]));
firstCondIndex++;
firstCondKey = value[1];
secondCondIndex = -1;
}
if(value[2]) {
// For Second Condition
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey].push(createObj(value[2]));
secondCondIndex++;
secondCondkey = value[2];
}
if(value[3]) {
// For Products
// We just push the string
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey][secondCondIndex][secondCondkey].push(value[3]);
}
});
function createObj(val) {
// We need to initialize blank array so we can push the children of that element later on
var obj = {};
obj[val] = [];
return obj;
}
console.log(finalObj);

Call truncate function inside .each loop when populating select options?

I'm trying to dynamically populate a select and call a truncate function in the loop... like below. I want to send the option text down to the function, truncate it if it's longer than 20 chars and send it back before it gets added to the option and appended to the select.
$(function() {
for (var i = 0; i < response.option.length; i++) {
var truncatedText = truncate();
var text = response.option[i].name;
truncate(text);
$("select").append("<option>" + truncatedText.text + "</option>");
}
});
function truncate(text) {
var textLength = text.length;
if (textLength > 20) {
text = text.substr(0, 20) + '...';
}
return text;
}
After jsfiddling for a while I landed on a working solution. Is there a more elegant way to do this?
https://jsfiddle.net/kirkbross/pcb0a3Lg/9/
var namesList = ['johnathan', 'tim', 'greggory', 'ashton', 'elizabeth'];
$(function() {
for (var i = 0; i < 5; i++) {
var name = namesList[i];
$('#names').append('<option>' + name + '</option>');
}
var selected_option = $('#names').find('option:selected').val();
var truncated = truncate(selected_option);
$('option:selected').text(truncated.new);
$('#names').change(function(){
var selected_option = $(this).find('option:selected').val();
var truncated = truncate(selected_option);
$('option:selected').text(truncated.new);
});
});
function truncate(selected_option) {
var nameLength = selected_option.length
if (nameLength > 4) {
selected_option = selected_option.substr(0, 4) + '...';
}
return {new: selected_option}
}