Javascript var with a newline using MVC Model property - javascript

I have to set a Javascript variable to equal a property in my MVC model.
I am doing this to detect if any changes were made to a textbox, this is setting the "original" value.
My Javascript code looks like this:
var initVal = '#Model.ReferralHistoryDetail[1].ReferralComments';
I am getting an error, which I assume is due to this containing carriage returns in the comments.
Uncaught SyntaxError: Unexpected token ILLEGAL
The HTML being rendered in this case is putting the closing quote on a newline, and that is the error being shown in the developer console.
For example, the rendered HTML is:
var initVal = 'blah blah blah
';
What is the proper way to handle this?

You want to use the JavaScriptStringEncode command to encode the string in a javascript compatible way.
var initVal = '#HttpUtility.JavaScriptStringEncode(Model.ReferralHistoryDetail[1].ReferralComments)';

If you replace \n character by \,
you will have a valid syntax for multiple lines string.
So that should work
var initVal = '#Model.ReferralHistoryDetail[1].ReferralComments.Replace("\n","\\")';
I found other ways to allow multiple line string in javascript,
in this answer.

You need to create an extension method that replaces the new line character with tags.
Or use the method HtmlEncode
like this:
var initVal = #Html.Raw(HttpUtility.HtmlEncode(#Model.ReferralHistoryDetail[1].ReferralComments).Replace("\n", "<br />"))

You cannot access Model properties from JavaScript like that, JavaScript cannot do anything with your model.
Create a variable up the page
#{ var value = #Model.ReferralHistoryDetail[1].ReferralComments;
Then access value in javascript, though not sure why you don't just render directly on page why do you need javascript unless I am missing something

Related

Passing a Django Object to Javascript

Below is the simplified version of my code
view.py:
context['colorObj'] = Colors.objects.all()
Now on template, I can just loop through {{colorObj}} to get the individual values inside the object.
However on JavaScript, this is not the case.
If I want to assign to a variable my colorObj, it just does not work(or maybe I am wrong).
Here is I first thought I should do:
JavaScript:
var colorObj = {{colorObj}};
the value of colorObj is still empty, and there are warning marks on the {{}}. Others suggested to use "" on the Javascript like var colorObj = "{{colorObj}}"; but JavaScript just treat this as a simple String.
Other suggestion is this:
from json import dumps
...
colorObj = Colors.objects.all()
context['colorObj'] = dumps(colorObj)
Then on JS:
var colorObj = {{colorObj| safe}};
But I got an error Object of type QuerySet is not JSON serializable pointing the error to the dumps line.
Note, I am using Django3.1.5
Though I asked about how to get the data from db to Javascript with this method, I proceeded to a different method since it matches my use case. I used #Mahdi Firouzjah's answer for this.
you could use ajax in templates and __ serialize in backend side.
then using javascript you're able to work with that object.

Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this:
var UserName = #Request.QueryString["UserName"];
But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this:
var UserName = ANT -- ANT 37690 / THIRD PARTY
So is there a way to do some kind of sanitation on it so it wouldn't crash? I guess there are illegal characters in that value for JS?
The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s].
One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace.
var UserName = #new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);
The shorter version of this for a string is:
var UserName = "#System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";
or overloaded version that wraps the result in double quotes:
var UserName = #System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);
You need to include quotes for the value.
var UserName = "#(Request.QueryString["UserName"])";
Otherwise the name will come through verbatim in your code and cause the problems you are seeing.
There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario.
If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library.
var sanitizedJsVariable = "#System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

Using ColdFusion variable with line breaks in JavaScript

I have a text area that accepts line breaks. The content of that text area is saved in a coldfusion variable (lets call it #fieldVal#). So, my variable contents look like
textline 1
textline 2
Later on, I use that variable in JavaScript
document.all.fieldName.value = "#fieldVal#";
However, when the JavaScript hits the page, it looks like this:
document.all.fieldName.value = "textline 1
textline 2";
and the script breaks because the first line doesn't end in a semicolon.
I tried setting a JavaScript variable to the ColdFusion text then doing a replace(), but I still hit the same issue with the line not ending correctly.
I think I'm missing something obvious but I am just not seeing it. Can someone tell me what I'm missing here?
Use the JSStringFormat() function. It is designed to escape meta characters in JavaScript
Escapes special JavaScript characters, such as single-quotation mark,
double-quotation mark, and newline.
https://wikidocs.adobe.com/wiki/display/coldfusionen/JSStringFormat
document.all.fieldName.value = "#JSStringFormat( fieldVal )#";
If you're using ColdFusion 10+ or Lucee Server, use EncodeForJavaScript().
https://wikidocs.adobe.com/wiki/display/coldfusionen/EncodeForJavaScript
Option 1
document.all.fieldName.value = "#Replace(trim(fieldVal), chr(10) & chr(13), ' ', 'ALL')#";
Option 2 (Possible that the same issue occur in this too.)
Try using ToScript()
ToScript(fieldVal, valueVar)
Toscript initializes a variable with the coldfusion variable value and you can use like any JS global variable.
document.all.fieldName.value = valueVar;
Option 3 (If you need in HTML form)
Use coldfusion function ParagraphFormat() which changes line breaks into <br/>.
I stumbled upon a code snippet that worked. Its a bit...convoluted, but it works.
document.all.fieldName.value = "#Replace(Replace(URLDecode(Replace(Replace(URLEncodedFormat(fieldVal), "%0D", " ", "ALL"), "%0A", "", "ALL")),CHR(34),"", "ALL"),CHR(39),"", "ALL")#"

jQuery, how to test of a variable is a text node, containing no markup?

http://jsfiddle.net/DerNalia/zrppg/8/
I have two lines of code that pretty much do the same thing
var doesntbreak = $j("hello");
var breaks = $j(" ");
​The first one doesn't error, but the second one throws this
Syntax error, unrecognized expression:
should'nt they both behave the same?
any insight as to how to solve this?
in the actual method I'm using, ele is from the Dom, so it could eb a text node, or any other kind of node.
UPDATE:
the input to the function that I'm using that I noticed this takes selection from the dom.
updated example: http://jsfiddle.net/DerNalia/zrppg/11/ <- includes html markup.
So, I guess, my question is, how do I test if something is JUST a text node? and doesn't contain any markup?
In general, you cannot create standalone text nodes with the jQuery function. If a string isn't obviously HTML, it gets treated as a selector, and is not recognized by jQuery as a valid selector.
Assuming you want to parse arbitrary strings (which may have HTML tags or not), I suggest something like var result = $('<div></div>').html(' ').contents();. Place your your HTML or text string in a div to parse it and then immediately extract the parsed result as a jQuery object with the list of elements. You can append the resultant list of elements with $(parentElem).append(result);
try this:
function isTextNode(node){
div=document.createElement('div');
div.innerHTML=node;
return $(div).text()==$(div).html();
}
And " " is'nt a valid selector if you want to find a elements containing some text you must use the :contains selector http://api.jquery.com/contains-selector/
Internet Explorer (older versions at least) don't have built in "querySelector" functions, so the Sizzle engine has to do the work directly. Thus, the slightly different tolerances for bogus input can cause differences in error reporting.
Your selector expression " " is equally invalid in all browsers, however. The library is not obliged to quietly accept anything you pass it, so perhaps you should reconsider your application design.
If you want to check for entities, you could use a regular expression if you're confident that it's just a text node. Or you could get the contents with .text() instead of .html().
So, I have to thank Apsillers and Rolando for pointing me in the right direction. Their answers were very close, but gave me the information I needed.
This is what I ended up using:
TEXT_NODE = 3;
objectify = function(n) {
return $j("<div></div>").html(n).contents();
}
function textOnly(n) {
var o = objectify(n);
for (var i = 0; i < o.length; i++) {
if (objectify(o[i])[0].nodeType != TEXT_NODE) {
return false
}
}
return true;
}
And here is a jsFiddle with some test cases, that neither of the original code submissions passed.
to pass, it needed to handle this kind of input
"hello" // true
"hello<b>there</b>" // false
"<b>there</b>" // false
" " // false
Not actual answer, but may help someone with similar issue as mine and loosely related to this question. :)
I was getting same issue today, so fixed by removing
Changed:
var breaks = $j(" ");
to:
var breaks = $j(" ".replace(/&.*;/g, ""));
Here I am removing , < etc...
Note: value at is dynamic for me, so it can be anything.

In JMeter and BeanShell, how can I make a variable lowercase?

In JMeter's User Parameters, how can I make a variable lowercase?
Left column
my_lowercase_variable
Right column
${__BeanShell('${my_variable}'.toLowerCase())} //fails
or
${__javaScript('${my_variable}'.toLowerCase())} //fails
Such that ${my_lowercase_variable} is lowercase of ${my_variable}. Tried with quote and without and escaping and such. No luck. Any tricks or tips welcome.
Note to self.
It turns out to be a two liner in BeanShell Sampler rather than a __BeanShell command. Not exactly in the examples unfortunately.
I added the BeanShell Sampler under the Thread Group, then made a variable. No parameters in the form were required only the two liner script below. As long as I don't change the variable I can copy the data to another variable, change that instead, and then make a Value reference to that wherever needed.
First define a variable in some User Parameters or such
ie:
Name: my_initial_reference
Value: ITS IN CAPS
Add a Bean Sampler under the User Preferences or definition list (just next, it's not a child process)
Put in:
String blah = "${my_initial_reference}"; //
vars.put("blah", blah.toLowerCase()); //${blah} = "its in caps" now available
Now under that with Name/Value pairs I can map ${blah} as the value to whatever process name requires it.
Note that the Debug response will still show the initial value in caps but you'll also see blah=its in caps which is what I wanted to use.
Simply can add a function
${__lowercase(${VAL},VALUE)}
${__uppercase(${VAL},VALUE)}
Note: VAL can be correlated or paramiterized value (e.r VAL= TO LOWER or VAL= TO UPPER). We can use this function in beanshell (pre-processor/post-processor/sampler). Jmeter version using (2.6).
Can use it where ever we want in the script as ${VALUE}.
${__javaScript('${foobar}'.toLowerCase())} does work. If the output is ${foobar} instead of desired value, it means that the variable has not been declared
Note that variables are defined only after the "User Defined Variable" component has been parsed. Variables cannot be reused within a single "User Defined Variable" component e.g.:
The second row in that image will not be able to refer to the variable my_variable in the first row. To be able to refer to the first variable, two "User Defined Variable" components is needed. The first variable will be in the first component and the second variable in the second one, e.g.:
With that, ${my_lower_case_variable} will successfully be converted into some value.
${__BeanShell("${my_variable}".toLowerCase())} works too. (Note that Bean Shell requires double quotes. The code in your question uses single quotes.)
Another way is to use vars.get:
${__javaScript(vars.get('my_variable').toLowerCase())}
${__BeanShell(vars.get("my_variable").toLowerCase())}
Hmmmm, your bean shell code didn't work for me. The bean shell sampler returned:
Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String blah = AAP; vars.put("blah", blah.toLowerCase()); //${blah} now availab . . . '' : Typed variable declaration : Void initializer
I added two double quotes to solve it:
String blah = "${my_initial_reference}";
vars.put("blah", blah.toLowerCase()); //${blah} now available
The beanshell and JavaScript functions in this use will fail, because they don't import the packages you need in order to use .toLowerCase.
If you really need to use a function to convert case (rather then declaring them as lowercase in the first place), you may need to write a full beanshell post-processor script in order to import the needed packages.
http://jmeter.apache.org/usermanual/functions.html#__BeanShell
http://jmeter.apache.org/usermanual/functions.html#__javaScript
http://www.javadocexamples.com/java_examples/org/apache/jmeter/
var blah = "${my_initial_reference}";
blah.toLowerCase();

Categories

Resources