Passing script variables as parameters - javascript

I've a javascript variable which i need to pass as a parameter to the included file.
Ex:
var var1 = "test";
Now i need to pass this 'var1' to an include file like this
<%#include file="text.jsp?param1=" + var1 %>
Will this work ? Help me out.
Or, is there any other way around without submitting the form, I need to pass this variable data to that included file which is presented in the same jsp.

No, this can't work, because the include will be parsed on the server side, long before the javascript var is available.
Instead, you need to add a request parameter to the page url:
<%#include file="text.jsp?param1=${request('someparam')}" %>

No, it won't work. Your JSP is compiled and run server-side, and the Javascript is executed much later on the client-side.

JS processed after JSP. Learn how server side and client side code is executed

Related

How can I mix Razor and Javascript in a VB project?

I have the following javascript/jquery snippet in a View of my vb.net based asp.net mvc project. I am trying to hit up the Browse method of my Neutrals controller.
<script type="text/javascript">
window.location.href = '/Neutrals/Browse?AreaOfLaw=' +
$('#search_area').val() + '&WebRegionID=' + $('#search_region').val();
</script>
I'd like to replace the url string with an #Url.Action, but I can't figure out how to fix the Razor syntax and that of the query parameters that I have.
I've fiddled with it for a good while and most of the time I can't even get it to compile.
Unfortunately, I don't think you can do it.
The problem is that you need those JavaScript variables - i.e. #Url.Action is executed when page is rendered on the server and you don't have JavaScript variables then.
Sure, you can construct part of url on the server, but the querystring part will need to be in JavaScript.
Use is directly as
window.location.href = '#Url.Action("action","controller")'

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.

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);
%>

To assign the value of a JavaScript variable into Java variable

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.

Rails: generate .js file at runtime

I've a .js file in my public/javascript folder, I want to include a dynamicaly generated value in this file.
Is it possible to have a .js file dynamicaly generated, something like public/javascript/my_javascript.js.erb
Thanks
No, not in /public. But you can generate a js file from a standard Rails action, if you like. I wouldn't recommend this, because mixing backend with javascript code is one of the fastest ways to create an unmaintainable and confusing application.
A better solution might be to render a script tag in your layout (above the js includes) to dynamically set a js variable. Then use MY_VAR wherever you need it in the js.
<% javascript_tag do -%>
var MY_VAR = '<%= value_of_my_var || "defaultVal" %>';
<% end -%>
How about a javascript controller as detailed in this railscast:
http://railscasts.com/episodes/88-dynamic-select-menus
Now if you want to only instantiate this dynamic value at runtime then you could cache it or store in an instance variable, depending on where the data's coming from.
You can keep your existing javascript having it by storing the rails variable in a js variable in the dynamic file, as long as page load completed.
Yea don't do it, you are much better off keeping the code static and using rails to generate data, in say the form of a JSON.

Categories