I am trying to set a ruby instance variable's value to the latitude and longitude values.
How would you set the value of an instance variable inside a javascript function?
Something like this?
<script>
if (geoPosition.init()){ geoPosition.getCurrentPosition(geoSuccess, geoError); }
function geoSuccess(p) {
<% #lat_lng = p.coords.latidude + "," + p.coords.longitude %>
}
function geoError(){ alert("No Location: Won't be able to use Maps functionality"); }
</script>
Something is telling me I need json.
You are not understanding where and when code runs.
Ruby (on Rails, or otherwise) runs on the server. It creates the HTML+JS+whatever that gets sent over the Internet to the client.
The client (web browser) receives this code and, among other things, executes JavaScript code.
You cannot, therefore, have your Ruby variables be set as the result of running JavaScript code…without contacting the web server again.
You need to use AJAX (or some other, lesser technology) to send a request back to the web server when that function is called.
For example (using jQuery's jQuery.post):
function geoSuccess(p){
$.post('/newcoords',{lat:p.coords.latitude, long:p.coords.longitude});
}
and in some controller somewhere:
def newcoords
#lat_lng = [params[:lat],params[:long]].join(",")
end
Related
I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/
I try to pass my JS variable into razor, my script fragment:
select: function (event, ui) {
var docID = ui.item.DoctorCode;
#{
string org_code = _unitOfWork.Doctors.GetById("").OrganizationCode;
}
doctorOrgLabel.text('#org_code');
}
In GetById() method i want to pass JS variable docID. I'd appreciate any help!
I try to pass my JS variable into razor
This sentence makes strictly no sense at all.
Razor is a view engine used by the ASP.NET MVC framework running on the server to produce some HTML template.
javascript on the other hand is a client side language running on the client. Once the HTML template is rendered to the client and javascript starts to execute there's no longer such notion as Razor.
If you want to pass some javascript variable to the server you have a couple of options:
make an AJAX call to the server
set the value of this variable in some hidden field inside a form and submit this form
use window.location.href to redirect to the server and passing the variable as query string parameter
store the javascript variable in a cookie which will be sent to the server on subsequent requests
I am working on one script which has been called from the websocket . This page of code is of html.erb
It pass variable to the javascript, and from that javascript variable i want to assign it to ruby variable ,
Here is the code
function set_color(val1,val2)
{
<%background_color_id = %>
var obj_color_id = '<%=background_color_id ='+val2+'%>' ;
console.log(obj_color_id)
}
The result from console log is +val2+
If I pass var obj_color_id = '<%=background_color_id ='val2'%>' ;
The result from console log is val2
Please help me assign javascript variable to ruby variable
You cannot do this. Javascript runs Client side, Ruby runs Server side.
You can't do that. All values <%= are translated on server side and their values are send to client. There is no ruby on client side. You have to send request to your websocket or http server in order to pass some data to server.
Actually, if I understand your code (your question is not well phrased, unfortunately), the simple solution is:
1- Assign a value via server-side code:
function set_color(val1,val2)
{
var bkgdColorId = "<%= background_color_id %>";
var obj_color_id = bkgdColorId;
console.log(obj_color_id)
}
2- (Or,) Assign a value from client-side code:
function set_color(val1,val2)
{
/** pseudo-code **/
on-click-event: makeAjaxCallToServer(){
urlForWebService, { color: val2 }
}
}
Using some jQuery (if assigning to server from client-side event) would greatly facilitate this process.
i m doing a database project using mysql as the database and jsp for my frontend part along with javascript and ajax for interaction.
Now the problem is i need to assign a java script variable which is having a string to a jsp variable.
I did this using the following statement?
<% String str="document.write(s)"; %>
where "s" is already defined as
<script type="text/javascript">
var s="hello world";
<script>
but i m getting error in the assignment statement(which is shown in bold above) as incorrect syntax?
the error i m getting is-
check the manual that corresponds to your MySQL server version for the right syntax to use near '<script>document.write(s)</script>'
what is the error in this stmt or is there any other method in doing this assignment?
Can anyone help in doing this?
You cannot do this. The JSP statement is executed server-side, before the execution of the Javascript statement, that is executed client-side after the browser received the http response.
It is not clear your goal, but if you only need to display in the page the value of a javascript variable, you can use:
trivial javascript:
document.write(s);
targeting existing element:
document.getElementById('myElementId').innerHTML = s;
using jQuery:
$('#myElementId').html(s);
If i understand correctly you are trying to build and execute a sql query based on user input that is handled by javascript. As ADC said this can not be done since jsp is executed server side therefore before browser executes javascript. What you can do is create the sql query and pass this as a parameter a different jsp/servlet (or the same if you can handle this case) which will execute the query
In the first page where sql statement is constructed in variable s you should put something like this
<script>
var s = "hello world";
function createLink(){
document.getElementById('mylink').href= 'page2.jsp?statement='+s;
}
window.onload=createLink;
</script>
<a id="mylink" href=""/>Click to exexute query</a>
which create a link to you second page (page2.jsp) passing the statement as parameter.
Now in page2.jsp you should retreive the parameter value like
<% String statement = request.getParameter("statement") %>
and then execute your query.
Even better you should use a servlet instead of a jsp page to perform the query. You could read a tutorial for jsp/sevlets to see how this can be done
eg. http://www.laliluna.de/articles/posts/first-java-servlets-jsp-tutorial.html
How can I access an JavaScript variable from within an JSP page ?
My guess is that you're probably running Javascript on the client (in the browser), and Java in your JSP pages on the server. You can't access a client-side variable on the server. You can send a client-side variable's value from the client to the server for server-side processing. You'd probably do that via an Ajax call, or just by submitting a form.
Edit For example, this Javascript code sends the value of the foo variable to the server side page 'test.jsp' using the field name "foofield" (slightly different name to be clear). This uses Prototype, but jQuery, Closure, and all the other libs can do much the same thing, just with slightly different syntax:
Server-side Java (in the JSP) — this is just like getting fields from a form that's been submitted:
String foo;
foo = request.getParameter("foofield");
Client-side Javascript (using Prototype's Ajax.Request):
// Our client-side `foo` variable
var foo = "Hi there";
// Send it to the server via Ajax (Prototype version)
new Ajax.Request('test.jsp', {
parameters: {foofield: foo},
onSuccess: handleSuccess, // Function to call on success; not shown
onFailure: handleFailure // Function to call on failure; not shown
});
If you prefer jQuery for the client-side, here's that Prototype code rewritten for jQuery's ajax function:
// Our client-side `foo` variable
var foo = "Hi there";
// Send it to the server via Ajax (jQuery version)
$.ajax({
url: 'test.jsp',
data: {foofield: foo},
success: handleSuccess, // Function to call on success; not shown
error: handleFailure // Function to call on failure; not shown
});
You can't access it directly. That's because this is how a page is rendered:
1. On the server, the JSP code runs and generates HTML/JavaScript.
2. The HTML/JavaScript is sent to the client's browser.
3. The browser then renders the HTML and runs the JavaScript.
As you can see, the JavaScript is run way after the JSP runs, so they can't directly access each other's variables.
What you could do is output JavaScript code which initializes a variable based on a value in the JSP code. For example, if you generate code like this (excuse my syntax, I don't know JSP):
<script>
var JSPValue = /*jsp code that prints the value of a variable*/;
//rest of JavaScript code...
</script>
Then the JavaScript can accss JSPValue, just because it will have been put there by the server. For example, when sent to the browser, it might look like:
<script>
var JSPValue = 42;
//rest of JavaScript code...
</script>
Not possible. You can access a JSP variable in javascript but the javascript variable can not be accessed in JSP.
As the javascript is running on the client side and the JSp is running at the server side,it is not possible to access the javascript variable in jsp code,but u can acess that javascript variable in the server side by passing that variable along with the request as request parameters,As the request parameters are there in the request object which is available to jsp code ,u can access them.