This question already has answers here:
How to pass a javascript variable to server side method
(3 answers)
Closed 7 years ago.
Here is an example:
JavaScript:
var b = 'Banana';
var list= <%= getJson() %>; // want to pass b?
C# Method:
using System.Web.Script.Serialization;
....
public string getJson(string x)
{
var list = new List<object>{new []{ "1","Apple"}, new []{ "2",x}};
return (new JavaScriptSerializer()).Serialize(list);
}
How can I pass variable b when I call getJson() from JavaScript?
The problem is, the server-side code executes and generates the page (including the javascript which is just text at this point). The page is then sent to the browser where the javascript is executed.
By that time, it's too late to do anything server-side.
Your options are:
Do a GET/POST/similar of the whole page back to the server, with the new variable from JS in a form field. This is trivial but causes a full-page refresh and is becoming less and less desirable.
Use a Javascript Ajax request to pass the variable back to the server and ask it for updated content. Use the response from the server to update the page for the user
The documentation for how to do the latter using jQuery is available here and there are literally thousands of examples around Stack Overflow.
Remember, anything called inside the <% ... %> tags get processed on the server side before the page even loads. If you need to dynamically load information from the server based on a variable, you need to make an AJAX request.
If you are able to, the easiest way to do this is with jQuery.
Related
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 5 months ago.
as stated, I am trying to dynamically populate a [shortcode] value in WordPress so that it puts the appropriate value in the field before it dumps the shortcode and all of the scripting happens in the plugin that outputs the complex code.
as of right now, I am able to properly output the value i want as seen here:
var url = window.location.href;
url = url.split('#').pop().split('?').pop().split('docsid=').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
var docsid = ('"' + page + '"')
console.log(docsid);```
This works as expected, my problem is, i'm trying to populate this field:
document.write(real3dflipbook id=docsid);
based on the code that the shortcode is dumped to, it looks like the shortcode is running first, then attempting to run my inputted javascript.
I have to console.logs running; one within the page itself, another in the embed.js file
the embed.js file console.log is working as it should be and that is the value output i'm hoping to get from my code.
1_633dbda152374 embed.js:144:16
the documents console.log is kicking up an error that it is producing from the embed.js file whenever i try to document.write(real3dflipbook id=docsid)
Uncaught SyntaxError: expected expression, got '<' documents:607:15
The code from the embed.js that I believe is where it is getting hung up is here:
var containerClass = bookContainer.attr("class")
var containerId = bookContainer.attr("id")
bookContainer.removeClass(containerClass).addClass(containerClass + "-" + containerId)>
console.log(containerId);
here is what the output code ends up looking like in the final page:
don't have enough points to embed yet
the top bit of highlighted garbage in the image is what happens when i attempt to document.write();
the bottom bit highlighted in blue is what SHOULD happen if it were properly updating the shortcode.
Any ideas or solutions on this? any help would be greatly appreciated!!
You can not just insert a shortcode parameter via javascript. The shortcode is rendered by the backend on page load. To dynamically set shortcode params you would need to make an AJAX call to a custom function in the backend which returns your shortcode with the specified parameters.
More information on Wordpress AJAX can be found here https://codex.wordpress.org/AJAX_in_Plugins
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to do front-end timer that would precisely show time left (in minutes and seconds).
This timer is supposed to count, even when user left the site or even close browser.
Although I thought of simple way to do the back-end part of it, I have no idea how to do it front-end, since I don't know JS or jQuery for that matter.
I could use gems, but most of them are using cannon to kill a fly. No need for scheduling since I don't need callbacks.
All I want to do is simple timer, where I pass rails variable with time of finish and counts down and stops when it reaches 0.
Here is what I found so far, but how do I pass rails variable into JS/jQuery?
#Edit for possible duplicate. This question is about said timer, but from rails point of view.
What you want to do is creating a container that will display your text and use javascript to update it's content. To tell the (client-side) javascript to what time it shall count down, you might create a hidden field containing that value, and read it out using jQuery. (Note: Passing the value could also be archieved through AJAX+embedded ruby in the JS-file, but it is much tougher to understand, and creating a hidden field in your html.erb should do your job even a bit faster!)
Retrieving the hidden field's content (a.k.a. the moment in time that your countdown is leading to):
var end_time = $('hidden-field').text();
#hidden-field {
display:none;
}
<span id='hidden-field'><%= time %></span>
(Note: As rails comes with jQuery, using it saves a lot of headdache. However, usually including the jQuery-library for this would be considered a "cannon to kill a fly". Also, make sure to use the correct CSS-Selecter within the jQuery call.)
You could also simply add this to your html.erb to assign a variable:
<script type='text/javascript'>var end_time = <%= time %> ;</script>
Depending on the format of your time (datetime vs unix timestamp vs...) you then let Javascript do the math. As rails usually saves Daytime-elements in the database, this should work:
var time_left = Math.abs(new Date(end_time) - new Date());
To insert into your page, do this:
$('#result').text(time_left);
#result {
// Some styling here
}
<p id='result'></p>
To make it work automatically from that point, combine the last two to a function like
var time_left;
function getTimeLeft() {
time_left = Math.abs(new Date(end_time) - new Date());
$('#result').text(time_left);
}
This last call will run your function every second
setInterval(getTimeLeft, 1000);
I did not test the code, but it should work or at least give the basic idea how you could do it. If you run into errors, please comment.
Happy coding.
P.S. Jacob's answer is shorter and more on the point. Try it first and come back here if you need to go further.
The js timer you found will do nicely.
The simplest way to pass a RoR variable into the js would be to use standard controller (.rb) -> view (.html.erb) communication channel.
In view:
<% <statement> %> - for conditionals and other pieces of non displayed code
<%= <statement> %> - for displaying variables etc.
<%# <statement> %> - easy way to comment ruby code
Example of what you want to do could then be:
Let us have a controller site_controller.rb:
class SiteController < ApplicationController
def index
#time_variable = 5.hours
end
end
Now we can create a view for this (site/index.html.erb):
(Let the startTimer(duration, display) be defined already)
<div id='time'></div>
<script>
window.onload = function () {
var timer = <%= #time_variable.to_i %>;
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>
Hope this helps.
There are a lot of ways to pass data from the back-end to the front-end in Rails.
First of all, there is the possibility of actually performing a request to the server to get back some data. In your case, I think this is overkill.
Another option would be to add the information in your view via the DOM. An often used pattern is to add data attributes to elements. Here's some references to get you started in jquery or plain javascript.
You can pass data to an element in your ERB template like so
<div id="timer" data-startdate="<%= get_date %>"></div>
and then have the front-end read this value and start the countdown appropriately.
Another option would be to expose a javascript variable to your window object, by including it in a script in your ERB template
<script>var startDate = '<%= get_date %>';</script>
Then front-end can then access window.startDate.
Good luck!