calling javascript on document.ready - javascript

My jquery will not run my java script function on document ready.
cont += "<script>";
cont += "$(document).ready(function() {Puma.getReasonForBTI()});";
cont += "</script>";
JS function
Puma.getReasonForBTI = function() {
var reason = document.getElementById("reasonId").value;
var msql = "SELECT Pid FROM tPid WHERE Reason = 'reason'";
sql = "action=getReasonForBTI&sql=" + encodeURIComponent(msql);
objAjaxAd.main_flag = "getReasonForBTI";
objAjaxAd.SendQuery(sql);
}
Any help would be appreciated.

Why not just add the DocReady to your JS?
Puma.getReasonForBTI = function() {
var reason = document.getElementById("reasonId").value;
var msql = "SELECT Pid FROM tPid WHERE Reason = 'reason'";
sql = "action=getReasonForBTI&sql=" + encodeURIComponent(msql);
objAjaxAd.main_flag = "getReasonForBTI";
objAjaxAd.SendQuery(sql);
}
$(document).ready(function() {
Puma.getReasonForBTI()
});
EDIT:
Also, I would send reason by itself and Sanitize it server side, then put it into a query. Sending a SQL query over Javascript/AJAX is just asking for trouble.
Faux-Code:
sql("
SELECT Pid
FROM tPid
WHERE Reason = ?
", $ajax.reason)
DOUBLE EDIT
Also, putting reason in single quotes in a string does not evaluate the value of reason. Just figured I'd save you some future headache
var foo = "bar";
console.log("The value of foo is 'foo'");
=> "The value of foo is 'foo'"
console.log("The value of foo is " + foo);
=> "The value of foo is bar"

Try a chrome browser and the Development tools (F12).
Take a look at the errorconsole.
Fix the error
Change your Code, because Someone can use YOUR code to delete any data from the underlying database
update
var reason = document.getElementById("reasonId").value;
// reason is entered directly byy a user (or Mr. EvilHacker).
var msql = "SELECT Pid FROM tPid WHERE Reason = 'reason'";
// Here you create a SQL, which may sounds like this:
SELECT Pid FROM tPid WHERE Reason = ''; DROP table tPid;--'
if the evil hacker entered ';DROP table tPid;-- into the textbox. Look at owasp.org for further information

Related

Cannot find method moveThreadToInbox((class))

Sometimes, when running the addon it will throw out the following error:
Error with the add-on.
Run time error.
Cannot find method moveThreadToInbox((class)). [line 102, function:,file:Code]
Other times, it works perfectly fine.
I have tried to handle this how Google does in the demo here
But still, get the same error. In fact, thinking about it... this probably isn't the best way to do it. As the query may return a subject with the same string. So I then tried to use the ID for the new mail, but that wouldn't play nicely with moveThreadToInbox.
The code and error messages are below:
The line of code that the error is referencing is:
GmailApp.moveThreadToInbox(newMailSearch[0]);
Full code section:
function editThreadSubject(e) {
var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);
var newSubject = e.formInputs.newSubject;
var firstMessage = GmailApp.getMessageById(e.messageMetadata.messageId)
.getThread()
.getMessages()[0];
var oldSubject = firstMessage.getSubject();
var thread = GmailApp.getMessageById(e.messageMetadata.messageId).getThread();
thread.getMessages().forEach(function(message) {
GmailApp.setCurrentMessageAccessToken(accessToken);
var messageId = message.getId();
var email = getEmail(messageId, accessToken);
var unencoded = Utilities.newBlob(
Utilities.base64DecodeWebSafe(email.raw)
).getDataAsString();
var updatedEmail = unencoded.replace(
"Subject: " + oldSubject,
"Subject: " + newSubject
);
email.raw = Utilities.base64EncodeWebSafe(updatedEmail);
var newMail = Gmail.Users.Messages.import(
{
raw: email.raw
},
"me",
Utilities.newBlob(email, "message/rfc822"),
{
deleted: false,
internalDateSource: "dateHeader",
neverMarkSpam: true,
processForCalendar: false
}
);
var newMailId = newMail.id;
var query = ["Subject:" + newSubject];
var newMailSearch = GmailApp.search(query);
GmailApp.moveThreadToInbox(newMailSearch[0]);
Gmail.Users.Messages.remove("me", messageId);
});
var notification = CardService.newNotification().setText(
"The subject has been updated"
);
var actionResponse = CardService.newActionResponseBuilder()
.setNotification(notification)
.setStateChanged(true)
.build();
return actionResponse;
}
It should insert the new mail into Gmail, delete the old mail and move the new mail in the inbox. As I said, it works some of the time so I'm stuck trying to figure out why it's not working when it doesn't!
If anyone can point me in the right direction, it would be fantastic and save me going prematurely bald through pulling my hair out!
You should probably put some type of test between this var newMailSearch = GmailApp.search(query); and this
GmailApp.moveThreadToInbox(newMailSearch[0]); to insure that what is returned meets the approach value and or type requirements for the function.

GlideAjax request doesn't return any response

I'm newer in servicenow developing.
I try to create a bundle "Script Include" - "Client Script".
Using background script I see, that my script include works fine.
But when I try to call this include via client script, it doesn't return any response.
Here is my method in Script Include:
usersCounter: function () {
var gr = new GlideRecord('sys_user');
gr.query();
var users = gr.getRowCount();
gs.info('Number of users'+ ' ' + users);
return users;
And here is my client script:
var ga = new GlideAjax('SCI_Training_ScriptIncludeOnChange');
ga.addParam('sysparm_name', 'usersCounter');
ga.getXML(getUsers);
function getUsers(response) {
var numberOfUsers = response.responseXML.documentElement.getAttribute("answer");
g_form.clearValue('description');
console.log(numberOfUsers);
And I have null in my console.
What have I missed?
Irrespective of why it's not working, you probably want to change your server side GlideRecord to use GlideAggregate instead, and just let mysql return the row count:
var gr = new GlideAggregate('sys_user');
gr.addAggregate('COUNT');
gr.query();
gr.next();
var users = gr.getAggregate('COUNT');
gs.info('Number of users'+ ' ' + users);
return users;
Doing a GlideRecord#query with no where clause is essentially doing a "SELECT * FROM sys_user", bringing over all the data, when all you're asking for is the row count from the metadata in the result set.
Beyond that, make sure your Script Include properly extends AbstractAjaxProcessor and has the client-callable field set to true per this:
https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/script/server_scripting/reference/r_ExamplesOfAsynchronousGlideAjax.html
You can try to debug your getUsers() method. Try to check what the object structure of response is.
You could also use
var ga = new GlideAjax('SCI_Training_ScriptIncludeOnChange');
ga.addParam('sysparm_name', 'usersCounter');
ga.getXMLAnswer(getUsers);
function getUsers(response) {
var numberOfUsers = response;
g_form.clearValue('description');
console.log(numberOfUsers);
}

Mirth - Send multiple HL7 messages during one polling interval

In Mirth, I have a JavaScript Reader connector and in the source, I have a call to a stored procedure. This procedure returns multiple rows. Is there any way to script it so that for each row returned from the procedure, I can generate the message and send appropriately? The other option that I am already aware of is to script it to generate only 1 message and have the polling interval set to every 100ms or so in addition to changing the procedure. Any help or insight would be greatly appreciated.
var procedure = 'exec dbo.mystoredprocedure';
objresult = dbConn.executeCachedQuery(procedure);
while (objresult.next())
{
var msg = <HL7Message/>;
msg.MSH['MSH.1'] = '|';
msg.MSH['MSH.2'] = '^~\\&';
msg.MSH['MSH.3'] = 'MedicalRecords';
msg.MSH['MSH.4'] = 'Application';
msg.MSH['MSH.5'] = 'Test';
msg.MSH['MSH.6'] = 'Something';
msg.MSH['MSH.7'] = DateUtil.getCurrentDate("yyyyMMddHHmmssSSS");
msg.MSH['MSH.8'] = '';
msg.MSH['MSH.9']['MSH.9.1'] = 'ADT';
msg.MSH['MSH.9']['MSH.9.2'] = 'A08';
msg.MSH['MSH.10'] = DateUtil.getCurrentDate("yyyyMMddHHmmssSSS");
msg.MSH['MSH.11'] = 'P';
msg.MSH['MSH.12'] = '2.5';
.
.
.
.
return msg;
}
Yes, you can return a List with multiple messages. Each element in the list will be dispatched to the channel as a separate message.
Great thanks! I did some digging and found what I was looking for.
var messages = new java.util.ArrayList();
messages.add(message1);
messages.add(message2);
return messages;

Running a javascript function based on statechange

Following the answer in this stackoverflow question, I am trying to run the following code. But the myfunction takes only one google visualization event. So Is the following code is valid? Or how to handle multiple statechange google visualization events in a single function?
var categoryPicker1, categoryPicker2;
function drawVisualization() {
// etc.
categoryPicker1 = // etc...
categoryPicker2 = // etc...
// Register to hear state changes.
google.visualization.events.addListener(categoryPicker1, 'statechange', myfunction);
google.visualization.events.addListener(categoryPicker2, 'statechange', myfunction);
// etc.
}
function myfunction() {
var whereClauses = [];
if (categorypicker1) {
whereClauses.push("something1 = '" + document.getElementsByClassName('goog-inline-block goog-menu-button-caption')[0].innerHTML + "'")
}
if (categorypicker2) {
whereClauses.push("something2 = '" + document.getElementsByClassName('goog-inline-block goog-menu-button-caption')[1].innerHTML + "'")
}
whereClause = whereClauses.join(" AND ");
// do something....
}
Not really clear from your question, but I assume you're building the SQL query to your database from the selected items in the CategoryPicker. Despite being an EXTREMELY bad/dangerous thing to do (building SQL client side, and sending it to a server), this should be possible by just grabbing the selectedItems from your CategoryPicker, and joining them with " AND ". Like:
values = categoryPicker1.getState().selectedValues;
values = values.concat(categoryPicker2.getState().selectedValues);
var args = values.map(function(_) { return "'" + _ + "'"; });
console.log(args.join(" AND "));
I wouldn't do this if I were you. I would pass the arguments up to the server, and remap them there (after appropriately filtering them, etc). Again this is very dangerous.

Nested getJson() & PHP PDO

I have looked at other questions and answers regarding this, but can't seem to wrap my head around it...
I have a javascript function:
function getStates(theDiv){
var stateGroupData;
var stateData;
var theGHtml = "";
var theHtml = "<h4>MyPage</h4>";
theHtml = theHtml+"<h5>select a state...</h5>";
$.getJSON("getStateGroups.php", function(data) {
stateGroupData = data;
theHtml = theHtml+"<ul>";
$.each(stateGroupData, function(i,jsonData) {
theHtml = theHtml+"<li><a href='#"+jsonData.groupName+"'>"+jsonData.groupID+"</a></li><br/>";
var theSQL = "getStates.php?gid="+jsonData.groupName;
theGHtml = theGHtml+"<div id='"+jsonData.groupName+"'>";
$.getJSON(theSQL, function(data2) {
stateData = data2;
$.each(stateData, function(i,jsonData2) {
alert(jsonData2.stateName);
theGHtml = theGHtml+"<span sname='"+jsonData2.stateName+"' lat='"+jsonData2.centerLat+"' lon='"+jsonData2.centerLon+"' zom='"+jsonData2.zoom+"'>"+jsonData2.stateName+"</span> ";
});
});
theGHtml = theGHtml+"</div>";
});
theHtml = theHtml+"</ul>";
});
theDiv.html = theHtml+theGHtml;
}
The second (ie. nested) getJson does not return any thing... Both PHP files just use PDO to request data from the SAME table. I run the SQL in each file without any issues, so the SQL seems OK.
Is this an sync v. async issue with the calls to getJson?
Is this an sync v. async issue with
the calls to getJson?
Probably. I think this is your problem:
stateData = data2;
Try changing that to:
var stateData = data2;
The first one sets a global variable. The second one sets a variable that is local to that function.
You might benefit from refactoring this whole process such that you only need to make one AJAX call. It looked like you were pulling individual people associated with a group. You'd get better performance on the server from a single script which can, when needed, return people associated with the group but otherwise just returns the group.
Remember, every AJAX call is another hit to your server.

Categories

Resources