Scope of JavaScript Variables? - javascript

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.

Related

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

calling a server side function from javascript without using ajax

I am trying to do the following :
function redirectContactOnClick(contactId) {
var enc=<%= QueryStringModule.Encrypt("cont="+ contactId)%>;
alert(enc);
//window.location = "Contacts/AddEditContact.aspx";
}
QueryStringModule.Encrypt is a function inside a c# class, the page raise an error saying :The name 'contactId' does not exist in the current context
You won't be able to pass your javascript variable (contactId) to C# method. Suggest to look a different solution for that, for example, making Generic Web Handler (.ashx) and pass there your contactId via ajax and get back whatever you expect from your Encrypt call.
You can call Server side(C#) function from javascript.
First you have include your script inside a ScriptManager runnable at server.
Then the javascript function can call the c# function (which is having an attribute of ([System.Web.Services.WebMethod] and must be static) can be accessed.
eg.
PageMethods.QueryStringModule.Encrypt("cont="+ contactId);
on client-side, and
[System.Web.Services.WebMethod]
public static void Encrypt(string id)
{
// Do something
};
on server-side
(Source: http://www.codeproject.com/Questions/727256/how-to-call-server-side-function-from-javascript)
For to call the Server Side member the only mode is do a request HTTP or sync (POST Page) o async (AJAX)
you don't call a server function directly
in the you case
receive an error because contactId not is an page's member you can comunicate with these way
ASP.NET Client to Server communication

How to use JavaScript variable in Razor?

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

Set ruby instance variable inside javascript function

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

assign javascript variable to ruby variable

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.

Categories