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
Related
I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.
#RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
public String getRcaResult(Model model, String flight_id) {
...
JSONObject all = new JSONObject ();
...
model.addAttribute("all",all);
return "dfi/rca";
}
I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:
<script type="text/javascript">
var all= "${all}";
</script>
But if I try the same importing a Javascript file in the JSP, it doesn't get anything:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>
In all.js:
var rcaresults = JSON.parse('${all}');
Are there any way to read the Spring model attributes in a Javascript file?
Thanks in advance.
JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.
If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.
e.g <script>var paramOne =<c:out value="${all}"/></script>
when you use src, your browser (and not your backend) will try to fetch the javascript file from
"${pageContext.request.contextPath}/resources/js/all.js"
so the file is not processed by the server as a ModelView.
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
var search= document.getElementById('appMenu').value
document.location.href= '${createLink(controller: 'application' , action:'ajaxAppSearch', params: ['query': search])}'
The element appMenu is a text field, so I am getting the value that the user enters into the text box to pass into a search controller. However, it keeps telling me that the params query is null. It seems that search isn't being passed into the create link method. Anyone have a suggestion?
Grails (controllers, GSP and tags, etc) are working on server side. JavaScript on client side. And this link is prepared before sending data to browser, and before JavaScript can pass its variable into GSP tag.
But you can prepare base link on server side, and add extra parameter on client side, by using javascript, like:
var search= document.getElementById('appMenu').value;
document.location.href= '${createLink(controller: 'application' , action:'ajaxAppSearch')}?query=' + escape(search);
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.