HTTP input to javascript variable remains undefined - javascript

Okay, so I'm fairly new to javascript and I'm working on the front-end of a webapplication for my internship, and this just utterly baffles me.
I have a select and an input element, both of which feed into a message model for a database Procedure Call through .POST(). I've done this in other scripts in the project, but here it won't work no matter how I try to assign the values.
Here's the code:
var cctOldSelect = document.getElementById("ConceptToCopy");
var cctOld = cctOldSelect.options[cctOldSelect.selectedIndex].value;
var cctNew = document.getElementById('NewConceptName').value;
console.log("cctOld: " + cctOld + "; cctNew: " + cctNew);
if (cctOld !== "" && cctNew !== "") {
console.log("model creation started.");
var model = {
p_cct_code_old: cctOldSelect.options[cctOldSelect.selectedIndex].value,
p_cct_code_new: document.getElementById('NewConceptName').value,
p_specialty_layout: null
};
console.log("model creation ended.");
}
console.log("cctOld model: " + model.cctOld + "; cctNew model: " + model.cctNew);
output:
cctOld: 1020H; cctNew: 1021H
model creation started.
model creation ended.
cctOld model: undefined; cctNew model: undefined
I've tried multiple ways:
p_cct_code_Old: $scope.<ElementID> //both with and without .value
p_cct_code_Old: document.getElementById(<ElementID>)
var cctOld = document.getElementById(<ElementID>); p_cctOld: cctOld
None of which work. Why won't it assign a value?

The problem in this case is that you create a new object called "model" and with two attributes called "p_cct_code_old" and "p_cct_code_new", then you are trying to access two attributes called "cctOld" and "cctNew" out of scope.
The JS interpreter when you are trying to access a non existing attributes do not throw an error, instead he return an undefined value.
The thing that I suggest to make the things work is:
var model = {};
var cctOldSelect = document.getElementById("ConceptToCopy");
var cctOld = cctOldSelect.options[cctOldSelect.selectedIndex].value;
var cctNew = document.getElementById('NewConceptName').value;
console.log("cctOld: " + cctOld + "; cctNew: " + cctNew);
if (cctOld !== "" && cctNew !== "") {
console.log("model creation started.");
model.p_cct_code_old = cctOldSelect.options[cctOldSelect.selectedIndex].value;
model.p_cct_code_new = document.getElementById('NewConceptName').value;
model.p_specialty_layout: null;
console.log("model creation ended.");
}
console.log("cctOld model: " + model.p_cct_code_old + "; cctNew model: " + model.p_cct_code_new);
Tell me if this solution helped you !

Related

How to append event listener script to dynamically created element formed from server side event data

I've looked through various similar questions but honestly I don't understand any of the answers (such as they are) in order to apply any of them to what I've written. I'd really appreciate some help as I'm extremely new to this and I'm very lost!
I'm attempting to update an existing page used by moderators for clearing created data as it comes in from users. It uses server side events to check for new items, the old version uses regular forms but the page takes too long to refresh after submitting data. I'm trying to use to set the form data in the background without the need for a refresh but I'm struggling to get the event listeners to attach to the visual elements. They are created dynamically from the event source data. Visually the output looks how I want it to, but it's not behaving as it needs to. One response to a similar-ish question said don't trust the console log, it could be working, but it definitely isn't, the process on the receiving end is a copy of the existing form handler for the old page, so I know that works.
I'm unsure if it's a syntax error or if I need a different approach, the errors I'm getting look like this - it can't find the element I want it to attach the script to:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at :1:37
at EventSource.source.onmessage (MOD.php:39)
This is what I've written on the receiving page:
window.onload = function() {
var last = "";
var lastqueue = "";
var source = new EventSource("MOD-data.php");
source.onmessage = function(event) {
var mydata = event.data;
var data = mydata.split('&&');
var upddate = (data[0]);
var queuedata = (data[1]);
if (mydata != last) {
last = mydata;
if (queuedata != lastqueue) {
var Qdata = queuedata.split('||');
for (let i = 0; i < Qdata.length; i++) {
var itmdata = Qdata[i].split('.');
var itmID = "Q" +(itmdata[0]);
var exists = document.getElementById(itmID);
if (exists === null) {
var itmclass = (itmdata[1]);
var itmbg = (itmdata[2]);
var itmwho = (itmdata[3]);
var itmimg = (itmdata[4]);
var rewbox = "<div id=\"" + itmID + "\" class=\"Qitm " + itmclass + "\" style=\"background:#" + itmbg + "\">" + itmwho + "<input type=\"image\" class=\"rew\" name=\"submit\" src=\"/web/rewards/" + itmimg + ".png\"></div>";
document.getElementById("Qcon").innerHTML += "" + rewbox + "";
var newScript = document.createElement("script");
var inlineScript = document.createTextNode("document.getElementById(" + itmID + ").addEventListener(\"click\", Qclear, true);function Qclear() {\$.ajax({type: \"POST\",url: \"MOD-queue-clear.php\", data: \"timestamp=" + itmID + "\"})}");
newScript.append(inlineScript);
document.getElementById(itmID).appendChild(newScript);
};
};
lastqueue = queuedata;
};
document.getElementById("debug").innerHTML = "<!--" + queuedata + "-->";
};
};
};

Creating record using JS and JSON not correctly using owner value

I'm attempt to create a record in Dynamics 365 using JavaScript however the Owner field is not being set properly. The record creates just fine if I remove the setting of the 'ownerid' field. I have also tried formatting the guid both in lowercase and uppercase with no success (see comments in code). The fields are displayed as expected in the alert.
When the script is run both with the code that makes the guid lowercase or not, I get the following error:
Error: An error occurred while validating input paramters: Microsoft.OData.ODataException: A node of type 'StartArray' was read from the JSON reader when trying to read the contents of the property 'ownerid'; however, a 'StartObject' node or 'PrimitiveValue' node with null value was expected.
var managingDirector = Xrm.Page.getAttribute("new_managingdirector").getValue();
var md_id = managingDirector[0].id;
var md_name = managingDirector[0].name
var md_entityType = "systemuser"
//md_id = md_id.replace(/[{}]/g,"");
//md_id = md_id.toLowerCase();
//md_id = "{" + md_id + "}";
if (managingDirector != null) {
console.log(managingDirector[0]);
alert("MD is " + md_name + " with id " + md_id + " and type " + md_entityType);
} else {
alert("MD is null");
}
var md_owner = new Array();
md_owner[0] = new Object();
md_owner[0].name = md_name;
md_owner[0].id = md_id;
md_owner[0].entityType = md_entityType;
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": md_owner
}
// create pm record
Xrm.WebApi.createRecord("new_practicemanagement", data).then(
function success(result) {
alert("Practice Management record created with ID: " + result.id);
// perform operations on record creation
},
function (error) {
alert("Error: " + error.message);
// handle error conditions
}
);
When I attempt to restructure the data variable like this (with both lowercase and uppercase ID)
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": {
name: md_name,
id: md_id,
entityType: md_entityType
}
}
I get the following error:
An error occurred while validating input paramters: Microsoft.OData.ODataException: Does not support untyped vvalue in non-open type.
When I see your code you have data i.e field and it's value as below
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": md_owner
}
Now if you look at my code owner id is set as
entity["ownerid#odata.bind"] = "/systemusers(58127B9D-AFBC-E811-A958-000D3AB42BE8)";
Below is the code which worked for me, I just tried creating contact record.
var entity = {};
entity.firstname = "Webapi1";
entity["ownerid#odata.bind"] = "/systemusers(58127B9D-AFBC-E811-A958-000D3AB42BE8)";
Xrm.WebApi.online.createRecord("contact", entity).then(
function success(result) {
var newEntityId = result.id;
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);
To make your life easier w.r.t developement try CRMRESTBuilder you will find most of your code auto generated here.

JavaScript Class Objects not returning value

I've been working with the Microsoft Bot Framework to create a bot that can interface between MS Teams and AWS. I've been trying to write some JS functions but have been unsuccessful in getting them to operate how I want them to.
Here is what I am currently working on and am stuck on:
I am creating a 'ping' like functionality so a bot user can ping an instance in AWS and receive its status whether its running and has passed the system checks or not. My code is currently able to take the user request for the ping, retrieve the information from AWS, and can even print that info to the console. However, when I am trying to retrieve that information back out of the object that I set it to and print it to MS Teams, it says my variable is undefined.
Some code snippets are below:
class aws_Link {
constructor (mT, ping_1, i_state, i_status) {
this.myTag = mT;
this.ping = ping_1;
this.instance_state = i_state; // I declare this here, but should I?
this.instance_status = i_status; // I declare this here, but should I?
}
//i_state and i_status are just passed NULL when the object is initialized
//so they would be holding some value, not sure if I have to do this
api_link () {
var mainLink = API_LINK_TAKEN_OUT_FOR_OBVIOUS_REASONS;
var myTagFill = "myTag=";
var ampersand = "&";
var pingFill = "ping=";
var completeLink = String(mainLink + myTagFill + this.myTag + ampersand + pingFill + this.ping);
var finalLink = completeLink;
finalLink = finalLink.split(' ').join('');
//set up API-key authenticication
var options = {
url: finalLink,
headers: {
'x-api-key': 'AWS-PRIVATE-TOKEN'
}
};
if(this.ping == "TRUE") { // if the user wants to use /ping
var res = request(options, function(error, response, body) {
console.log("PING REQUEST"); //debug
body = JSON.parse(body);
var h_state = body['instanceState'];
var h_status = body['instanceStatus'];
this.instance_state = h_state;
this.instance_status = h_status;
console.log("STATE: " + h_state); //debug
console.log("STATUS: " + h_status); //debug
});
}
}
pingFunction () {
var tmp = "Instance State: " + this.instance_state + " Instance Status: " + this.instance_status;
return tmp;
}
}
And here is where I call the api_link() function and pingFunction():
var apiLink1 = new aws_Link("MY_TAG_VALUE", "TRUE", "NULL", "NULL");
var completeAPILink = apiLink1.api_link();
session.send('Request complete.');
session.send("PING: " + apiLink1.pingFunction());
So essentially the user enters in some info which gets passed to where I create the "new aws_Link" which then a my understanding is, creates an object called apiLink1. From there, it makes the request to AWS in my api_link() function, which retrieves the info I want. I thought I was then saving this info when I do the: this.instance_state = h_state; & this.instance_status = h_status;. So then when I call pingFunction() again on apiLink1, I thought I would be able to retrieve the information back out using this.instance_state and this.instance_status, but all it prints out is undefined. Any clarification on why my current code isn't working and any changes or improvements I can make would be greatly appreciated.
Thanks!

Parse join query using Javascript pointer

I have a two parse objects 'Content' and 'Detail'
Below I have added a screen shot of both classes in their data browsers.
I have a column in 'Content' called descId which is the Detail objects objectId and is a pointer to the 'Detail' Class. I need to know how to obtain data from both classes. This is my attempt but var Details is undefined.
var iBeacon = Parse.Object.extend('Details');
var content = Parse.Object.extend('Content');
var query = new Parse.Query(iBeacon);
query.include('descId');
query.find({
success: function(results) {
// // Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
var Details = object.get('Details');
(function($) {
$('#iBeaconTable').append('<tr><td id = "uuid" >' + object.get('uuid') + '</td><td = "proxId">' + object.get('proximity') + '</td><td = "offerId">' + object.get('offer') + '</td><td class = "buttonRow"><Button id = "btnEdit" onclick = "openDialog()" class = "flat-button">Edit</Button><Button id = "btnDelete" onclick = "Delete()" class = "flat-button">Delete</Button></td></tr>');//<Button id = "editSave">Save</Button></td></tr>');
})(jQuery);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I am pulling my hair out on this and I really need dig out...regards.
You are causing yourself confusion by naming the property on the Content class descId. The fact that Parse internally uses a pointer structure with an ID is an implementation detail you don't need to worry about, as far as your code is concerned you'll be using a full Detail object all the time.
The actual error in your code is this line:
var Details = object.get('Details');
Change it to:
// should be using the property name
var Details = object.get('descId');

How to get information from Object in class in Parse.com using JavaScript

I have in parse.com the class MainBranch and it contains objects in columns Customer and Location which are pointing to another classes ((User and locations )) and I need some information from those two classes but I can not reach to them.
My output after running give me [Object Object]
My JavaScript code :
var order = Parse.Object.extend("MainBranch");
var query = new Parse.Query(order);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " Orders.");
var orid1 = results[2].get("OrderId")
document.getElementById("intro").innerHTML = orid1;
orid1 = results[2].get("Customer");
document.getElementById("intro1").innerHTML = orid1;
orid1 = results[2].get("TotalPrice");
document.getElementById("intro2").innerHTML = orid1;
orid1 = results[2].get("Location");
document.getElementById("intro3").innerHTML = orid1;
orid1 = results[2].get("Date");
var orid2 = results[2].get("Time");
document.getElementById("intro4").innerHTML = orid1+"<br>"+orid2;
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
from my searching I found that relations are necessary thus I tried many ways but i did not undrestand relations clearly and I did not find the solution yet. any help please !!
You can include those objects using
query.include("Customer");
query.include("Location");
This will fetch the related objects together with the MainBranch objects:
var customer = results[2].get("Customer");

Categories