Ruby code in a JavaScript function - javascript

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.

Related

How to pass javascript variable to django custom filter

Is there a way to access a JavaScript variable in django template code as shown below:
var tags_v1 = '{{ form.tags_1.value }}';
tags_v1 = tags_v1.split('{{ form.value_delim }}');
tags_v1 = tags_v1.map(function (item) { return '{{ $(item)|get_tag }}'; }) ;
I want to pass the value of "item" as variable to the custom filter "get_tag".
There is an important distinction between Django template code and in-browser JavaScript that you seem to be missing:
Django templates are built on the server side, while JavaScript executes on the client side.
That means that template code is always executed before JavaScript (as it is executed by the server before the page is sent to the client). As a consequence, it is impossible to mix JavaScript and Django code the way you want to.
For example, you seem to think that Django code inside JavaScript loop would execute multiple times. That, of course, is not true. Django code is executed once, on the server side, without any regard for JavaScript which is executed later in the browser (i.e., on a different machine!). For Django, your JavaScript code is just a meaningless text.
So, the answer is: if you want to split a string and apply a Django filter to each item, you need to split the string on the server side in Django. You can't split it in JavaScript and then manipulate the resulting list in Django, because Django runs much earlier, and on a different computer.

Ajax and Json with Rails

I followed Hartl's Rails tutorial where he does Ajax using RJS and sending javascript in the response to be executed on the client side to edit the DOM.
But what do you do if you want just JSON sent in the response and not send javascript. This also means the javascript to manipulate the DOM should already be in the html file on the client. Is there a tutorial as good as Hartl's book on how to do this in Rails. Presumably it would use Jquery and some other stuff maybe that I've not heard of to make the code not be a million lines?
My best attempt at an answer is that it really depends on the scope and complexity of what you're trying to achieve. Generally, JSON shows up in views. If your application does not require you to dynamically retrieve JSON, that is, you can load it all when the view is initially rendered, then you can set an instance variable in your view's controller like so
#my_json = some_object.to_json()
Then, your instance variable is available in your view
<script type = 'text/javascript'>
var theJSON = <%= #my_json %>
</script>
Now, your data is available in the DOM, parsed nicely into JSON.
If your application requires you to dynamically retrieve JSON after the controller/view are loaded, then you should probably look into using AJAX to hit a particular controller's method that returns the JSON that you desire.
Here's a good RailsCast that can hopefully help you along your way Passing Data to Javascript
You should take a look at Ajax in Rails 3.1 - A Roadmap.

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

Passing script variables as parameters

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

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.

Categories