sending parameters from ASP.NET to javascript - javascript

I want to call a javascript function from my ASP.NET (C#) code, I want to pass a variable (string) with another string like below:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text'+'"+myString+"'<br/>'another text);");
how should I pass these values? also I want to have new line in my tooltip (<br/>), what should I do? I've tried several ways (using ', + and other methods) to send all these values but I get javascript error, is there any sample? please help me
thanks

In that function, you could use the server side code tag.
var string = "<% = myString%>"

You are very close, keep in mind that when controls are generated on the server they are 'unrolled' into HTML on the client -- in other words the '+' sign is unnecessary as the client will only ever see the string (it has no notion of which part of the attribute value was generated in code vs. which part is hard coded on the server).
var toolTip = string.Format("This is text was added on {0}:{1}<br />this text is hard-coded", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()
var attributeValue = string.Format("tooltip.show('{0}')");
tag.Attributes.Add("onmouseover", attributeValue);

Try this:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text','"+myString+"<br/>another text');");

Two ways:
Method 1 (Jon Martin's way): Have a javascript variable populated by server information
Create a javascript variable on the aspx page: var myString = '<%= _mytring %>';
Populate _mystring on the code behind: public String _mystring = "your value";
Method 2: Just dump the variable out from the server side
Page.ClientScript.RegisterStartupScript(getType(Page), "var myString = '" + "your value" + "';", true);

Related

How can I pass the values of string variables defined in VB.net code into a CefSharp browser and call them by their name using Javascript?

First time user of CefSharp. I'm trying to use it with vb.net to automate some tasks in a website.
I created a ChromiumWebBrowser and pointed it to a website with 2 input fields Username and Password.
I managed to use javascript for filling the 2 input fileds with the 2 corresponding strings as follows:
document.getElementsByTagName('input')[0].value = 'MyUsername';
document.getElementsByTagName('input')[1].value = 'MyPassword';
and IT WORKS. I'm seeing the 2 fileds filled with the 2 strings. (The fileds have no Id. That's why the getElementsByTagName)
Now, I want, instead of the actual strings inside the javascript code, to pass the strings from variables inside my VB.net code. Something like:
VB.net code
Dim USER as String = 'MyUsername'
Dim PASS as String = 'MyPassword'
and the previous JS code to something like:
document.getElementsByTagName('input')[0].value = USER;
document.getElementsByTagName('input')[1].value = PASS;
but obviously not that!
I found some posts about putting in my VB code something like this
browser.JavascriptObjectRepository.Register("boundAsync", New BoundObject())
and a Public Class BoundObject
and pass it to JS code like
await CefSharp.BindObjectAsync("boundAsync", "bound");
but I'm confused on how to do it with the 2 strings I mentioned before.
How can I register the USER and PASS variables in VB.net and then call their values in JS to fill the input fields?
TIA
Yes I was doing that, just now!
in VB.net code
Dim USER as String = 'MyUsername'
and in JS code
document.getElementsByTagName('input')[0].value = '" + USER + "';
the trick is in the quotes. Instead of writing = USER
you put it like this '" + USER + "'

How to correctly read encoded get varible

I have a search engine that does the following things:
Read an input value and encode it using js, then redirect.
//read and save into `query` var
window.location.href = "/search/" + encodeURIComponent(query);
So if user enters
What is the meaning of & sign ?
The ulrl can't end up like this;
expample.com/search/What%20is%the%meaning%20of%20&this%20sign?
And instead get:
expample.com/search/What%20is%the%meaning%20of%20&26this%20sign%3F
Now when I dump the $_GET['parameters'] i get
string() "search/What is the meaning of "
I expect to get:
What is the meaning of & sign ?
I have tried:
$val = urldecode($_GET['parameters']);
But I have had no luck, Maybe I should change the way javascript encodes the url, what are your suggestions?
PHP decodes URL paramaters automatically into the $_GET superglobal as long as you're using the standard query string syntax. If you use your own syntax, you have to roll your own code (you already have custom code in the input form).
The raw URL can be fetched from $_SERVER['REQUEST_URI'] and parsed with the text manipulation tool of your choice. It's worth noting that this isn't an uncommon set up (many PHP frameworks do things this way).
You've mentioned that you're calling the following to obtain the value of the user's query:
$val = urldecode($_GET['parameters']);
This implies that a URL calling your PHP page would have a shape similar to the following:
http://foo.bar/?parameters=<the query here>
The important thing to include in the URL is ?; when a URL is parsed, the ? signals that whatever comes afterward is a URL-encoded query.
Thus, in your javascript:
window.location.href = "/search/?parameters=" + encodeURIComponent(query);
Then your existing code should work.
Just do
on client-side
window.location.href = "/search/" + query;
and on server-side
$val = urldecode($_GET['parameters']);

apple .replace() Html element generate by handlebar js

I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements.
For instance i have this role of p tag which display a row of data by handlebar js:
<p id="pre-region">{{region}}</p>
and the result of it is
1,44
and i 'd like to change it to
1+44
If you haven't had any experience of handlebar js then consider the tag be
<p id="pre-region">1,44</p>
how should i change from 1,44 to 1 +44?
UPDATE 1
Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax.
After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error.
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1%2B4
This is how may API looks like at the moment
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1+4
should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(',', '+');
</script>
I'll check out the handlebars js in case it does not work.
Update:
As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring):
decodeURIComponent('1%2B44'); // you get '1+44'
Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page.
Update 1
You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is:
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1%2B4
What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language.
Update 2
The solution above only replace the first occasion of comma to +. To solve that, simply use:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(/,/g, '+');
// Regular Expression is used here, 'g' for global search.
</script>
PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want:
<script>
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
}
// Another method to replace all occasions using `split` and `join`.
</script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go:
You could try this code in another js file that runs after handlebars:
var pre = $('#pre-region'); // defines a variabe for the element (same as
// document.getElementById('pre-region'))
var retrievedRegion = pre.innerHTML;
var splitten = retrievedRegion.split(',');
var concatenated = parseInt(split[0]) + parseInt(split[1])
retrievedRegion.innerHTML = "'" + concatenated) + "'";
or using replace():
retrievedRegion.replace(',','+')

Convert mail merge variable to sting with quotes in Javascript

I'm working in a proprietary system that has the ability to add HTML and Javascript to create custom pages. The system has the ability to insert user profile fields into the HTML/Javascript a mail merge like tag. In a project I'm working on I'm using a value from one of the users fields (User_Region) to append to a URL and create a personalized link to another system for each user.
I have been able to append the URL successfully when the value is numeric (12345) but not when it is text or alphanumeric. For example neither "Florida" nor "123456a" work.
Here's the code that I am using:
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = {User_Region};
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
In the code {User_Region} is the mail merge tag that I use to insert the variable from the user profile field. If the region variable is numeric like 123456 it works perfectly and it will output a URl like this:
https://www.mywebsite.com/index.php?id=123456
However if the region variable is text or alphanumeric like Florida or 123456a then the script does not work. Document.write does not output anything. It seems like the function either stops or breaks. I'm guessing this has to do with a data type issue, but I can't seem to figure it out.
If I hard code the variable as a string like this the function works perfectly.
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = 'Florida';
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
The above code will output a correct URL like this:
https://www.mywebsite.com/index.php?id=Florida
I have tried numerous ways to add the single-quote marks to the {User_Region} variable without success.
Does anyone have a suggestion for how I can make this work?
Thanks in advance for your assistance!
Have you tried encapsulating it in quotes as such:
var userRegion = '{User_Region}';
Because I guess your framework just replaces the {User_Region} with something else, please inform me if I got it wrong. I didn't quite get what this tag is. You see, in JS, curly braces are used to define Objects.

getting error while passing value from javascript to scriplet in jsp

I have a requirement where i need to pass a value from Javascript to a Scriplet in a JSP. i am aware that javascript is executed on client side and jsp on the server side.i have searched online and googled a lot but till now i am not able to find a solution that i am looking for. The JSP code is as below. both javascript and scriplet are in same jsp.
<script type="text/javascript">
var strUrl = window.location.href;
var aps = strUrl.toLowerCase().indexOf("values");
var modifiedString = strUrl.substring(aps+8);
var v = strUrl.indexOf(modifiedString);
document.write(v);
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st);
if(st.equals("0")){
out.println("test");
%>
<h1><div class="xyz">
<fmt:message>header.txt</fmt:message>
</div></h1>
<%
}else{
%>
<div class="pqr">
<fmt:message>header1.txt</fmt:message>
</div>
<%
}
%>
In the above code i am trying to pass a value from Javascript to a scriplet.
But i am getting a NumberFormatException when i try to parse that string and convert to int. looks like the variable st is not of a string type.
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st)
Can you please let me know what is the problem with the above code and how can i resolve the problem that i am facing now.
Thanks
Vikeng
The reason why you can't parse "<script>document.writeln(v)</script>" as an int is because it contains characters other than digits.
Even though it looks like it contains <script> tags - it's still not code that will execute or evaluate to a number. Because it's in quotes it's just a string. So "<script>document.writeln(v)</script>" looks the same to the parser as would "tic/v)neiwtm>oprs<citdun.rtl(<rp>".
This is somewhat of a moot point however, because unfortunately, you can't pass values to scriptlets. It's completely one-directional.
In order to get your page communicating with your java, you'll need to pass your params while requesting some handler.
For example, you could do some asynchronous JavaScript:
var asyncHR = new XMLHttpRequest();
var URL = "https://www.yourserver.com/intparser?st=v";
asyncHR.open("GET", URL, true);
asyncHR.send();
Then your request handler could take that parameter st, parse it or whatever you need to do, modify the model - adding this new value as an attribute, and then from JavaScript, reload the page.

Categories