To assign the value of a JavaScript variable into Java variable - javascript

I have encountered a situation where I have to assign the value of a JavaScript variable into Java variable.
Please suggest me a way to do it.
P.S: Assigning value of Java variable into JavaScript is something like this:
< Script>< %
String str = "abcd";
%>
var x = <%= a %>;
/Script>
I have to do opposite of it.

If Java is being used as the server-side language, by the time the page has been sent, Java has long finished (it doesn't run after the page has loaded). You may make a request to a page, sending the variable with the request, and that page may have Java handle the variable, though.

It is not even clear what you are doing, but I assume that the snippet you show is part of a template for a web page. You will not be able to get the variable directly - JavaScript will be running on another computer some continents apart!
But you can make the client communicate with the server, using AJAX.

Related

Get return value from JS code to C#

I want to get the answer of a window.prompt() alert box through the C# Code Behind file. It's just a one-liner of JavaScript code, so I thought I could even execute it from the Code Behind file. It doesn't really matter to me whether it's a <script> tag in the .aspx file or executed through the .aspx.cs file.
I thought of having the script executed (called from the C# part) and then having the return value assigned to a certain not visible field, but is there any better way to do it?
The obvious way would probably go something like this:
.aspx file:
<script>
function foo() {
document.getElementById('MyFieldID').value = window.prompt('Answer this question:', '');
}
</script>
.aspx.cs file:
////////////////////////////////////////////////
//MyFieldID.Text now contains whatever I want//
//////////////////////////////////////////////
What do you say? Is there any better way?
Better way is always opinion based. What I'd say is you have a few options, all depend on what you're doing. HTTP and ASP.NET provide us a few means of sending data to the server, there are 3 main ones before HTML5:
Query string
Form values
AJAX calls
If you're redirecting the user to a new page after they answer the prompt, you can just send them to yournewurl.aspx?promptAnswer=*whatever*
If you're doing a postback, then you can use a form value (this looks like what you're doing in your example). You can put an <asp:HiddenField> on the page and populate it from JavaScript before submitting the form.
If you need just the prompt response, but are not attempting to reload the page, you can make an AJAX call that sends the variable to the server (this still uses #1 or #2 to send the data, it just does it without reloading the page).
Which of those three options works best depends on your implementation. However, your solution should work just fine. However, since the control you'd likely be using to stuff the value into is a HiddenField it would be in MyFieldID.Value not MyFieldID.Text. The only other thing you have to deal with is if your MyFieldID is nested in some other controls (like a ContentPlaceHolder) such that the ClientID has naming containers pretended to it so it's really something like ContentPlanceHolder1_MyFieldID when accessed from JavaScript.

Ruby code in a JavaScript function

I'm new in the world of JavaScript, jQuery, and Ajax. I have a JavaScript function where I want to use the value of a JavaScript variable inside of embedded Ruby code. For example, below I want to use the JS p variable as an argument to the Ruby call to #r.search():
$(function (){
$('#data-select').on('change',function (){
var p = document.getElementById('data-select').value;
alert(<% j #r.search(+ p +) %>);
});
});
I want to know if i can do this? And if i can what's the syntax?
First off, I'm assuming this is Ruby on Rails (which you tagged it as). When using ERB you are telling Rails to first evaluate the embedded Ruby code to dynamically insert data that is on the server-side, and then send the file to the client over the internet where their web browser then evaluates the JavaScript.
So if this is what's in your file, and you passed a #user variable with a name method that evaluates to "John Smith":
// test.js.erb
alert("Hello <%= #user.name %>");
When that file is rendered, your server will evaluate it to this:
// test.js
alert("Hello John Smith");
And then send that over the internet to the client. Only once the client's computer has received this file will the JavaScript be evaluated. They (and the JavaScript) will therefore never see the embedded Ruby code. Therefore what you're doing cannot be done the way you have it because the Ruby code is evaluated before the JavaScript can set the p variable.
If you want to get information that resides on the server after the client has received the file and is running the JavaScript, you can use something called Ajax, which uses JavaScript to send data asynchronously back to the server. Check out this Rails guide for more details on that.
You Can't do it, because while rendering the view all ERb will be converted to HTML or relevant, so you don't have access tp the Ruby objects after rendering the view.
You can also pass the dynamic values from javascript to certain rails methods
Refer: http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/remote_function
But this rails method also will converted to ajax function after rendering.
The solution:
Try to send an ajax request and show the result in view.

pass variables to html page without using GET

I have a webpage on a raspberry pi. This page supports only HTML since I am using webIOpi. I can make use of python scripts and javascript.
When I link to this page hosted on the raspberry from outside I would need to pass some variables. but i do not want to put them in the URL as I would like to keep the URL clean.
Is there any other method i can use to pass values to this page using any of the above resources?
I don't know your markup, I got the same problem in a one-page-markup where content come and go (slide in and out) via javascript commands.
In my case I save some values in html attributes via javascript. This is a valid feature in HTML5, when you use a "data-" prefix for your value names (good explanation here) :
// Save it
element.setAttribute("data-foo", "bar");
// Get it
var foo = element.getAttribute("data-foo");
Note : reloading the page will unset the attributes ! ...but worked for me...

Passing the asp classic html as a string from client-side to server-side

I am having the next scenario (I can't change it). I have an classic asp page. In it, I have the asp code, the javascript code, and the VBscript code. When the user clicks the button confirm, the javascript function "confirm" is executed. In it, the page submits a form to itself.
What I want to accomplish is the next thing. Inside that javascript function confirm, I can easily get the web page html as a string. But what I want is to get that string in the VBScript part when the page processes the self-submit done. I have tried the next things:
Inserting in an asp input hidden control in the page, and load from JavaScript the needed string in that input. Afterwards I expected to get it in VBScript by Request("controlId/controlName"). But it fails me because the input hidden control can't have strings that large.
In the JavaScript confirm function, to load in a session variable in the string. But it looks like I can't write a client-side variable in a session variable.
To store through the JavaScript function a temporary file and passing it through a input file control. This I only have thought about it. Because i don't think that it is a good solution to store a temporary file in the client-side, and I still have the believe to find a better solution than this. Also I don't know exactly how to write files with JavaScript in the client-side.
I remember that I have tried all this, if I remember another thing that I tried, I will post it here.
I have slammed my face repeatedly against the desktop, but I can't find a solution to this. Any idea would be really helpful.
But it fails me because the input hidden control can't have strings
that large.
Use method="post" instead of method="get" in the form, and the data size is practically limitless. I.e. the limit changes from a few kilobyte to several megabyte.
But it looks like I can't write a client-side variable in a session
variable.
That is correct. The session variables only exist on the server side.
To store through the javascript function a temporary file and passing
it through a input file control.
That is a process in two steps, where each step in itself is generally impossible. You can't access the local file system using Javascript, and you can't set the file name of an input file control using Javascript.
So you want to get html page in your ASP using javascript?
Why do you want to do that. You can use your a form with a post method to send big string.

Calling Java inside JavaScript Function

Please tell me if we can call java inside javascript function ?
<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {
<% System.out.println("Hiiiiiiiii"); %>
}
</SCRIPT>
<FORM>
<INPUT type="button" value="call Java method direct" onClick = "getScreenDimension()">
</FORM>
</BODY></HTML>
While the answer of "No" is technically correct based on the phrasing of the question. You may want to read up on AJAX. It is a way for javascript to make a request to your backend code (in this case Java).
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.
My question to you would be, "What are you trying to do, and what do you expect to see?".
You have to realize that there are two different execution contexts. The first is the JSP itself whose code is executed by the JVM on the server-side, and the second is the Javascript that is executed by the browser. So when the code goes to the browser, you'll see: So the System.out.println will cause Hiiiiiiiii to be printed to the server logs, but you won't see anything on the browser. In fact, the Javascript code on the browser will look like this:
function getScreenDimension() {
}
Which is not valid Javascript code. The code in the JSP is run before the Javascript gets run on the browser. So to "run" Java code, you need to make a request to your server either by posting the form or with an AJAX call. This will cause Java code in the appropriate servlet or controller, to run.
UPDATE
After glancing at your code, it appears that you want to call a Java method directly. This is not possible with your current code. You might want to read up on AJAX. This will point you in the right direction.
JSP runs on the server. It generates a document which the server sends to the browser. That is the end of the involvement of JSP in the process. The browser then parses the document and runs any JS.
You can include JSP in a script element, it just has to output valid JavaScript.
You cannot have JSP that runs in response to JavaScript, other then when JavaScript causes the browser to issue a new HTTP request (either setting location.href, submitting a form, adding an image, or using Ajax, etc)
I think you have lack of understanding of what is going on here. Anything in middle of <% %> is executed when the page is first requested. Anything in javascript is executed when the browser calls it. What you have will never happen and there is no way to make it happen. However, you can use AJAX to do something like this but that's a different question.
Yes, you can. Use JSP expressions <%= %>. Example:
<aui:script use="aui-datepicker">
AUI().use('aui-datepicker', function(A) {
new A.DatePickerSelect({
calendar : {
dates : [ '<%="1/1/1970" %>' ],
}
}).render('#myDatePicker');
});
</aui:script>
Yes, you can call Java from Javascript, both if you mean the Java-VM on the server and on the client; i assume you mean the client (the VM in the browser); take a look here:
http://www.apl.jhu.edu/~hall/java/Java-from-JavaScript.html
You can. In JSF you can use PrimeFaces' component p:remoteCommand, which would contain action method. Call that remoteCommand by its name from JS and the java method will get executed.
JSF Page
<p:remoteCommand name='rmt' action="#{bean.doWork()}"/>
In JavaScript
function callJava {rmt();}
Use JSP code
<%
// Respond to the application with 1) result, 2) update, and 3) updateid values
String result = "blablabla";
out.print(result);
%>

Categories