how to pass javascript variable to the jstl code - javascript

I have something like the below code. I need to pass the variable selectedIndex to the JSTL code. How can I do this?
function updateSP(selectedIndex)
{
<c:if test="${entry.key eq IC.oList[selectedIndex]}">
}

First, you need the following concept right: Java/JSP runs at the server machine and produces a HTML/CSS/JS page. The server machine sends HTML/CSS/JS page over network (HTTP) to the client machine. Client machine retrieves HTML/CSS/JS and starts to interpret HTML to display a markup structure, apply CSS to style and position the structure and execute JS on the resulting the HTML/CSS.
There is no means of any line of Java/JSP code at the client machine. Rightclick page and view source. The only way to pass Java/JSP variables to Javascript is to just output them as if it's a Javascript variable so that it has instant access to it once it runs at the client machine. The only way to pass Javascript variables to Java/JSP is to just send a HTTP request with that variable as parameter and have Java/JSP to listen on that specific request.
More background information and code examples can be found in this article.

jstl is executed in server side so you can't pass a javascript variable to jstl.
What you can do is generate dynamic javascript using jstl.
Please use the tool to format your code.

Related

How to inject server variable to a client side js/html file

How can a Javascript variable set on a server(via properties file) be injected to an Angular js/JavaScript app?
There is a Java Jersey application that has client files (js, HTML, CSS, etc.) under the /src/main/webapp folder and there is a javascript variable that I would want to set before it gets served to the client. For example , please consider the following:
<script type="text/javascript">
var serverHost = "<%serverHost%>";
</script>
How can I replace the value of "<%serverHost%>" String with a value of my choice that will be evaluated at runtime? Preferably via properties.
The goal of this is that the client has Rest calls and the URL cannot be relative and has to be full because the application will be accessed via a different/middle man server, so ultimately the rest calls need to reach the originated host server. The value is need via a properties file so the application/same build can work on different environments.
Would appreciate any ideas.
Thank you
The problem you are trying to solve needs server side rendering.
In your case, for example,
You can retrieve the host URL from the properties file on the server side, pass it to the view using the controller, and in the view, using JSP tags, generate an HTML for which the serverHost variable is dynamically set
HOWEVER....
As you are using AngularJS, this type of rendering is clearly against Angular's philosophy.
You can create a constant in angular,
angular.module('myApp').constant('SERVER_URL', 'http://localhost:8000/');
You can set the value of this constant during the build.
OR
You can create a simple API where you'll retrieve the host url value from the properties file, preferably in JSON format, then you can simply call that API to set this constant value.

How to pass javascript variables into rails controller?

how to pass the date variable into erb puts command
function myDayClickHandler(eventObj){
var date = eventObj.data.calDayDate;
<%puts "asdf",date%>
};
Javascript and Ruby are something very different. Javascript is client-side, running in the browser. Ruby is run on the server side, separately from client-side code.
Ruby code (<% .. %> parts in your example) is run on the server.
Javascript code (var date = eventObj.data.calDayDate;) is executed in the browser. It's also executed after the Ruby code, when server has processed request and generated result page already.
If you want to know value of date on the server, you'll have to send it from the browser to the server in AJAX request. Any popular Javascript library will help with that.
To pass data to the Rails controller from Javascript, you will need to pass the data back through attaching query parameters in the url.
http://www.google.com?variable1=1&variable2=2
Then in the rails controller you access the variable using
params[:variable1] or params[:variable2]
You can use custom controller actions to perform an activity either using javascript to submit or render, or use traditional HTML. Javascript would be preferred for user experience.

How can I call javascript function in Model or Controller in Cakephp?

I have to call a javascript function from my Model or Controller. I can call it from the view file but how can I call a JS function directly from Model.
Is there a way to do that?
PHP is a server side language. This means the PHP file will get processed on the HTTP server and then deliver the generated HTML page to the client.
Javascript (JS) is interpreted on the the client (browser) and interfaces with the HTML and other remote resources.
Due to this model, PHP and JS know nothing about each other. So to call JS directly from the PHP file is not possible.
If you are looking to make a client browser call a JS function and the PHP script defines the values for the JS function you can use echo() and some string concatenation
//this is an example and will not run.
echo "<script>myJsFunction('" . $arg1 . "','" . $arg2 . "')</script>";
This will embed the JS function call in the HTML page returned to the client. Once the client renders the HTML page it will execute the function call as it comes across it.
If you could give an example of what you trying to do I might be able to give you a more accurate answer.
For a deeper explanation of the client server architecture and where things get executed have a look at Web Browser Client Server Architecture
No, try understanding the MVC pattern, the idea is that the model is not aware of the view and doesn't have to be. Also you can't call JS with php, which is a server side language and doesn't know anything about the client side scripts.
What you want is to implement long polling. I recommend you to learn and read about the basic technologies involved before trying to implement something.
http://en.wikipedia.org/wiki/Push_technology
http://en.wikipedia.org/wiki/Comet_%28programming%29

How far can I go with JavaScript?

I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.

How to use JSP tags in JavaScript?

How to use JSP tags in JavaScript file?
Is there any way?
JSP is a view technology which runs at the server side which you can use to write template text like HTML/CSS/JS in. You can use JSP taglibs and EL to control the page flow and output dynamically using Java code. This also concerns the JavaScript content/output. Once JSP has run, it basically produces a HTML page and sends it to the client side. You can use JSP to dynamically output back-end data as if it are JavaScript variables. For example:
<script>
var foo = '${someBean.someProperty}';
</script>
Once the HTML page (with CSS/JS inside) has arrived at the client side (rightclick page and view source, you won't see any line of Java/JSP code), then the HTML will start to be interpreted, the CSS will start to be applied and the JS will start to be executed. There's no means of Java/JSP code at the client side. If you view the generated source in the client, the above example would now look like:
<script>
var foo = 'somePropertyValue';
</script>
This way JavaScript has just instant access to server-side variables.
Now the other way round; the only way to let JavaScript access/invoke Java/JSP code is to actually send a HTTP request to the server side. This can be done several ways: doing a window.location to do a synchronous GET request, or doing a form.submit() to do a synchronous GET or POST request, or doing a XMLHttpRequest#send() to do an asynchronous request (also known from Ajax).
Alternatively you can also just let JavaScript set a (hidden) input field of a form so that it "automatically" get taken with the form submit whenever the user submits the form. Either way, the Java/JSP code at the server side will then be able to access JavaScript-controlled values the usual request parameter way.
To learn more about the wall between Java/JSP and JavaScript you may find this article useful.
I have wondered about this when I have values in my session or context I wanted exposed in the client side. I create a jsp file with javascript mime type which just include global variable values. Which I then include at the top of my page and reuse the values where necessary.
for eg:
**globalVar.jsp**
var ctxPath = "<%=request.getContextPath()%>";
**script.js**
ajaxURL = ctxPath + "/path/to/call?param=value";
You can even namespace this as outlined here
Yes, you can use JSP to generate JavaScript to send to the browser. Just point the <script> tag to a URL that leads to a JSP page that sets the MIME type of the response to "text/javascript".
No, you cannot use JSP tags in JavaScript in the browser. JSP is a server-side technology, which means that processing must be done on the server.
You can easily use java tags to assign to a java variable which is later invoked inside the javascript code.
<% String name="Peter" %>
and then in javascript..
<script type="text/javascript">
var _name = <%= name %>
#BalusC answer explain's well what is server-side and client-side programming. However I would like to highlight a point that if you really want to get run jsp within your javascript, then you can give it file extension .jsp instead of .js because what determines whether a file is a javascript file or not is what MIME media type. You can set MIME from JSP using:
<%# page contentType="text/javascript" %>
and now you can use jsp within your javascript like:
var someMessage = "${someMessage}"
var anotherMessage = "${anotherMessage}"/>"
and now, you can link directly to it as:
<script type="text/javascript" src="/script.jsp"></script>

Categories