jQuery Appending unwanted data - javascript

Some jQuery function in my code is inserting the string:
jQuery15206649508478338135_1314906667378
into user-provided feedback. This is happening from multiple forms and it's getting stored in the database, which is really annoying our users. One sample of such code:
$(".sendFeedback").live("click", function() {
var feedbackText = $(".feedbackText:visible").val();
var errorElement = $(".feedbackError:first");
if (isEmptyTrimmed(feedbackText)) {
errorOut(errorElement, language.pleaseEnterFeedbackText);
return false;
}
var sendFeedback = { email : userSettings.email, firstName : "",lastName : "",primaryRole : "", description : "<br />Feedback text: <pre>" + feedbackText + "</pre>",
sendNotification : false, isPartner : false , formType : 3};
callService("sendFeedback", sendFeedback);
currentMessage = language.thankYouForTheFeedback;
loadScreenByHash("mainScreen");
});
function callService(serviceName, data, callbackFunction) {
var json = $.toJSON(data);
json = "{ " + serviceName + ": " + json + " }";
$.post(serviceUrl, json,
function(response) {
if (callbackFunction) {
callbackFunction(response);
}
}, 'json').error(function() {
if (callbackFunction) {
callbackFunction();
}
});
}
The callService function directs to a Java server, so I'm doubting it's getting inserted there. The java server writes to the DB, so I'm pretty sure it's getting inserted in the javascript code.
It happens other places as well, and they follow the same formula: read user input with .val(), pass to callService (sometimes through additional JS function). A sample of the output data:
I created a quiz but can not figure out how to run it for my class.
there are no buttons that say run
quizjQuery15206649508478338135_1314906667378? Customer Name
I've also seen it appended at the end of a string. Let me know if anyone has seen this before.

I found the cause of the problem. User data was entered, sent to the database, but the database was not set for UTF-8. The problem occurred every time the character encoding was messed up in the database. When the database returned garbage, it would trigger the string to be added.
Changing the database encoding solved this problem.

Related

iterating and extracting data from xml in javascript on mirth

I'm using mirth connect 3.7, java version 1.8. i am new to both mirth and javascript. I have set up a channel destination to a javascript writer to get data out of xml files inserted into a mysql db. a sample section of xml file as follows:
...
<DG1>
<DG1.1>
<DG1.1.1>1</DG1.1.1>
</DG1.1>
<DG1.2>
<DG1.2.1>I10</DG1.2.1>
</DG1.2>
<DG1.3>
<DG1.3.1>R10.9</DG1.3.1>
</DG1.3>
<DG1.4>
<DG1.4.1>UNSPECIFIED ABDOMINAL PAIN</DG1.4.1>
</DG1.4>
<DG1.5/>
<DG1.6>
<DG1.6.1>A</DG1.6.1>
</DG1.6>
<DG1.7/>
<DG1.8>
<DG1.8.1>391</DG1.8.1>
</DG1.8>
<DG1.9/>
<DG1.10/>
<DG1.11>
<DG1.11.1>4252.21</DG1.11.1>
</DG1.11>
<DG1.12/>
<DG1.13/>
<DG1.14/>
<DG1.15/>
<DG1.16/>
<DG1.17/>
<DG1.18>
<DG1.18.1>N</DG1.18.1>
</DG1.18>
</DG1>
<DG1>
<DG1.1>
<DG1.1.1>2</DG1.1.1>
</DG1.1>
<DG1.2>
<DG1.2.1>I10</DG1.2.1>
</DG1.2>
<DG1.3>
<DG1.3.1>R10.9</DG1.3.1>
</DG1.3>
<DG1.4>
<DG1.4.1>UNSPECIFIED ABDOMINAL PAIN</DG1.4.1>
</DG1.4>
<DG1.5/>
<DG1.6>
<DG1.6.1>A</DG1.6.1>
</DG1.6>
<DG1.7/>
<DG1.8>
<DG1.8.1>391</DG1.8.1>
</DG1.8>
<DG1.9/>
<DG1.10/>
<DG1.11>
<DG1.11.1>4252.21</DG1.11.1>
</DG1.11>
<DG1.12/>
<DG1.13/>
<DG1.14/>
<DG1.15/>
<DG1.16/>
<DG1.17/>
<DG1.18>
<DG1.18.1>N</DG1.18.1>
</DG1.18>
</DG1>
...
I am trying to get the datapoints out of the xml iteratively so i can insert these diagnosis codes in a mysql table. my script at this point:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
var myNodeList = xml.querySelectorAll("DG1");
for (i = 0; i < myNodelist.length; i++) {
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES ("'+ $('AcctNum') + '", "' + $('MedRecNum') + '", "' + myNodelist[i]['DG1.3']['DG1.3.1'] + '")';
//do something with myVar to get a query...
dbConn.executeUpdate(myQuery);
}
} catch (ex) {
//handle any exceptions...
}
it runs without exceptions but i am not capturing the intended data obviously. Again, new to javascript, mirth and parsing xml. Questions:
obviously, i'm referencing the data points inappropriately, what is the nomenclature in javascript?
is there a dev environment in mirth that i can step through code and better troubleshoot?
are there any good recommended resources for javascript and xml as it pertains to mirth?
Mirth uses Mozilla Rhino for its Javascript engine. Rhino uses a deprecated standard called e4x for XML processing. If you search Google for e4x you'll find several pages at developer.mozilla.org with scary "obsolete" banners everywhere that can be helpful. The mirth user guide is very detailed when it comes to workflow within mirth.
https://github.com/mozilla/rhino
https://web.archive.org/web/20181120184304/https://wso2.com/project/mashup/0.2/docs/e4xquickstart.html (another good e4x resource)
https://www.nextgen.com/products-and-services/NextGen-Connect-Integration-Engine-Downloads (for the user guide)
I'm surprised querySelectorAll wasn't throwing an error. With minimal changes to your code:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
// This should work, but is not typically how hl7 segments are accessed. Would need to see more than a segment for typical usage.
var myNodeList = xml.descendants("DG1"); // returns type XMLList
// length is a function instead of property on XMLList objects
for (i = 0; i < myNodelist.length(); i++) {
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES ("'+ $('AcctNum') + '", "' + $('MedRecNum') + '", "' + myNodelist[i]['DG1.3']['DG1.3.1'] + '")';
dbConn.executeUpdate(myQuery);
}
} catch (ex) {
//handle any exceptions...
}
Using a for each loop and parameterized sql statement:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES (?, ?, ?)';
for each (var dg1 in xml.descendants('DG1')) {
dbConn.executeUpdate(myQuery, new java.util.ArrayList([$('AcctNum'), $('MedRecNum'), dg1['DG1.3']['DG1.3.1'].toString()]));
}
} catch (ex) {
//handle any exceptions...
}
You'll want a finally block after your try to close your database connection. If you remove the catch block, mirth will automatically set the message status to ERROR, write the exception to the server log, and fire an event which you can act on with a defined alert. That's usually easier than trying to handle the exception yourself.
Hi this is not quite right.
First ensure your data type is HL7.
Then do this (this is for insurance but you get the idea)
for each ( in1 in msg['IN1']) {
var effdate = in1['IN1.12']['IN1.12.1'];
// etc
}

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

Using Parse Javascript SDK Query GeoPoint withinMiles

I am creating a Parse App and I want to be able to get all objects within a certain distance of a single object using GeoPoints. Seems simple, but the following code returns [] (No matches):
app.get('/photos', function(req, res) {
var Photo = Parse.Object.extend("Photo");
var query = new Parse.Query(Photo);
query.equalTo("owner", Parse.User.current());
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
//res.send(results);
var photo = results[0];
// Create a query for places
var Photo = Parse.Object.extend("Photo");
var query = new Parse.Query(Photo);
// Interested in photos taken near this photo.
query.withinMiles("coordinates", photo.coordinates, 500000);
// Final list of objects
query.find({
success: function(photoObjects) {
res.send(photoObjects);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
Oddly, if I change the line
query.withinMiles("coordinates", photo.coordinates, 500000);
to
query.near("coordinates", photo.coordinates);
then it works without a hitch and returns all photos (Every single one has a GeoPoint within about a 5 mile radius of all the others in the sample data set, so I used a maxDistance of 500000 to test the extent of the issue).
The problem is I need to be able to limit to a specific radius, which is what I thought the "withinMiles" was doing. Any ideas what I may be doing wrong?
In case someone is finding this and shares my troubles, the following was the issue:
I was assuming that all "columns" of data objects in parse are treated as attributes. i.e. - You can access them using the . operator (photo.coordinates).
In fact, you must access them via photo.get("coordinates") to get the actual objects contained within the data structure.
Not sure why the above scenario was working in the case of the "near" function, but nonetheless the behavior works correctly when I started using the get accessor method for the Parse data objects.

Trouble with jQuery ajax

I am getting different errors in FF, Chrome and IE, but it all boils down there is an error with the data in $.ajax. Following is the code. Please go easy if I made a dumb mistake. I have spent hours researching this and can't figure it out. Any help appreciated.
Edited to include the error messages
FF Error message: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
Chrome Error message:Uncaught TypeError: Illegal invocation
IE9 Error message: SCRIPT65535: Argument not optional
Here is the code
mc.mc_data.click_tracking = [];
var sequence = 0;
var send_it;
// the container click event will record even extraneous clicks. need to change it to extending the jquery on click handler
$('#container').on('click', function(event) {
logClicks(event);
if(!send_it){
sendIt()
}
sequence++;
});
function sendIt(){
var tracking = mc.mc_data.click_tracking;
var url = '/ajax/click_trackin';
console.log("clicks["+sequence+"] "+$.isArray(tracking));
$.each(tracking, function(i,v){
console.log(i + v.innerText + " - " + v.sequence);
});
send_it = window.setInterval(function(){
$.ajax({
type: 'POST',
url: url,
data: {
clicks:tracking
},
success: function(response)
{
if(response.result.length<1){
console.log(response+ ': no response');
}else{
console.log(response);
tracking = mc.mc_data.click_tracks = [];
}
mc.mc_data.click_tracks = [];
clearInterval(send_it);
sendIt();
},
error: function(a, b, c){
console.log(a+" - " + b+" - "+ c);
clearInterval(send_it);
}
});
}, 5000);
}
//
function logClicks(e){
var temp_click = {
'business_id':window.mc.businessid,
'userid':window.mc.userid,
'timestamp':e.timeStamp,
'leg':window.mc.currentLeg,
'workflow': 'dummy data',
'sequence': sequence,
'type':e.type,
'target':e.target,
'parent': e.target.parentElement,
'id':e.target.id,
'class':e.className,
'innerText': $(e.target).text()
}
mc.mc_data.click_tracking.push(temp_click);
}
For data, you are meant to pass an object which will later be converted into a query string. You are passing the variable tracking, which contains stuff like e.target.parentElement, which is a DOM Node, containing really a lot of further properties (like other DOM Nodes!). The error can originate from either having problems converting a DOM Node into a query string, or creating a way too long query string. It would not make much sense to send a DOM Node to the server anyways.
Only send what is necessary and can be reasonably converted to a query string.

Jquery ajax functions stopped working

Ive been working on some jquery within a a page.
Now all of a sudden the post functions seem to have stopped working?
function deleteRow(OrderNo, LineNo) {
alert(OrderNo + ";" + LineNo);
$.ajax({
type: "POST",
url: "Ajax.aspx/DeleteRow",
data: '{' + 'OrderNo:"' + OrderNo + '",' + 'LineNo:"' + LineNo + '"' +
'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//$("#item").val(msg);
var data = jQuery.parseJSON(msg);
if (!data.error) {
$('#' + LineNo).remove();
}
else {
alert("Error" + " " + data.error);
}
},
error: function (msg) {
alert('Failure: ' + msg);
}
});
}
This is a jquery function which gives an error back 'Failure [object Object]'
the function DeleteRow does exist in Ajax.aspx and does work. Cant understand why all of a sudden the post functions would stop working??
[WebMethod]
public static string DeleteRow(string OrderNo, string LineNo)
{
SqlConnection myConnection = new SqlConnection(connStr);
myConnection.Open();
//Check if param exisits
string SQLst = "Delete from Saved_Order_Import where [Order No] = '"+OrderNo+"' And [Line No] = '"+LineNo+"'";
try
{
SqlCommand myComman = new SqlCommand(SQLst, myConnection);
myComman.ExecuteNonQuery();
}
catch (Exception ex)
{
myConnection.Close();
return "{\"error\":\"Error Line Not Deleted" + ex.ToString() + "\"}";
}
myConnection.Close();
return "{\"Success\":\"Line Deleted\"}";
}
console log
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
isRejected: function () {
isResolved: function () {
overrideMimeType: function ( type ) {
pipe: function ( fnDone, fnFail ) {
promise: function ( obj ) {
readyState: 4
responseText:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title>
</title></head>
<body>
<form name="form1" method="post" action="Ajax.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZAZAz479BJ9BS5KpwM0PauBgztmI" />
</div>
<div>
</div>
</form>
</body>
</html>
"
setRequestHeader: function ( name, value ) {
status: 200
statusCode: function ( map ) {
statusText: "parsererror"
success: function () {
then: function ( doneCallbacks, failCallbacks ) {
__proto__: Object
You problem is on this line:
'{' + 'OrderNo:"' + OrderNo + '",' + 'LineNo:"' + LineNo + '"' +
'}',
It should be like this:
'{' + '"OrderNo":"' + OrderNo + '",' + '"LineNo":"' + LineNo + '"' +
'}',
Notice the missing opening " before OrderNo:" and before LineNo:". The fix will produce a valid JSON string:
'{"OrderNo": "OrderNo Value", "LineNo": "LineNo Value"}'
It's suprisingly uncommon the knowledge that those double quotes are required for valid JSON.
Based on the response you posted, the server output was a HTTP Status 200 with a HTML Form as the response. Was this the desired format of the response?
You're telling the AJAX function to parse the response as JSON but no JSON came back from the request. Look at your console log. The exception is a parser error.
There are lots of improvements that could be brought to your code. I will try to cover at least some of them that are bugging me when hovering over your code at first sight.
The first thing that worries me is that your page method returns a string, in which you are manually writing some JSON. That's something you should never do. You should never manually serialize/deserialize anything. In any language. Never. You can read the following article to understand why. Page methods can return strongly typed objects and the ASP.NET infrastructure will take care of properly serializing them into JSON so that you don't have to worry about it. So let's start by introducing a model that your page method could return:
public class Result
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
As you can see in this model we have a boolean variable indicating the success or failure of the page method and a string variable containing the error message in the event of failure.
The next thing, and probably, the worst with your code, is the SQL injection vulnerability present in your ADO.NET snippet. Let's fix that by introducing parametrized queries and returning the model we have just defined:
[WebMethod]
public static Result DeleteRow(string OrderNo, string LineNo)
{
try
{
using (var myConnection = new SqlConnection(connStr))
using (var myCommand = myConnection.CreateCommand())
{
myConnection.Open();
myCommand.CommandText = "DELETE FROM Saved_Order_Import WHERE [Order No] = #OrderNo AND [Line No] = #LineNo";
myCommand.Parameters.AddWithValue("#OrderNo", OrderNo);
myCommand.Parameters.AddWithValue("#LineNo", LineNo);
myCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
return new Result
{
Success = false,
ErrorMessage = "Error Line Not Deleted" + ex.ToString()
};
}
return new Result
{
Success = true
};
}
The last step is to clean the client side code. Here you I would recommend you to use the JSON.stringify method to properly JSON serialize the javascript literal instead of using some string concatenations to manually build your JSON (read the article I have linked previously in my answer to understand why you should never manually serialize/deserialize anything => you should always use a proper qserializer for the given format).
$.ajax({
type: 'POST',
url: 'Ajax.aspx/DeleteRow',
data: JSON.stringify({ OrderNo: OrderNo, LineNo: LineNo }),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
// Notice how we use msg.d here. The ASP.NET Page Methods
// infrastructure will JSON serialize the response using this property:
// {"d":{"Success":"true"}}
var data = msg.d;
if (data.Success) {
$('#' + LineNo).remove();
}
else {
alert('Error ' + data.ErrorMessage);
}
},
error: function (msg) {
alert('Failure: ' + msg);
}
});
Also make sure that you have enabled page methods in the script manager of your page:
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
Remark: the JSON.stringify method is natively built-in modern browsers but if you need to support legacy browsers you could include the json2.js script to your page.
PHP devs (like me) who deal with jQuery, Ajax and other frontend technologies: "Suddenly not working" could mean that you added some debugging, some "echos" (PHP wrong way of debugging) and you forgot to check the entire stack in order of removing it. That debugging code you let there will cost long painful days of reviews and tests. Have you ever considered that? Follow these steps:
0 - (Please: Developers start counting from zero) - Directly call backend using URL only, whenever possible, instead of using ajax. You can grab a testing tool like these ones QA guys use - and we should get used on them too - there are many. Grow up. Go find one. Talk to QA guys. Do something. Now! :-)! Look at what you received: is it a valid JSON? Is it a valid XML? Is it a valid JSON/XML plus something that should not be there? Is it a valid JSON/XML but not the one you expected to receive? Probably this step is enough.
1 - Get used to the following useful ajax snippet (http://craigsworks.com/projects/forums/showthread.php?tid=3829) :
$.ajax({
url: 'http://localhost/formengine/index.php?r=site/ajax',
success: function(response) {
console.log(response);
}
});
2 - Test any other jQuery behavior instead of the one you are building. This step is just to make you feel better and recover that everyday rationality that pays your salary. jQuery, Ajax, PHP, .net stack, Java stack: they are friendly, nice and do want to be working for you. Sometimes it's just matter of handling head stuff: either an offline CDN, a URL that is wrong, source location may be wrong, these ordinary, everyday stuff. Place the CDN URL to the navigation bar: you shall be able to read the entire lib in your browser screen. Click on this: https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
3 - In the deepest moment of your desperation, have you placed any alert somewhere where it's not legal? Do not say "no"! Go testing it: google chrome, F12, a developers perspective frame opens and at the top right you can see the smallest red flag ever - yes: the smallest. Hear the voices in your head: click on it. A meaningful message will appear. If it's the case, fix the issue.
4 - Drive all the necessary efforts towards having a well defined deploying process. Copying and pasting are not professional approaches - and, believe me, you are the most interested ones on doing things right. There are many "best practices" references regarding deploying, considering, of course, the technology stack you guys use: follow them.
Good Luck to you all! Hope it helps!

Categories

Resources