I'd like to do something like that
function(){
<% ExampleClass sample = new ExampleClass(); %>
var ID = 4;
var something = <%= sample.getSomethingById(ID) %>
}
How can I pass this ID to the jsp expression?
Thanks for any suggestion, and sorry id the question is not so well formulated.
you can also use more advanced methods and tools, like Ajax and JQuery:
function submitToJsp(){
$.ajax({
type: 'POST',
url: 'mypage.jsp',
data: {
id: '123',
comment:$('#comment').val()
},
beforeSend:function(){
// this is where we append usually a loading image
},
success:function(data){
// successful request; do something with the data
$('#output').html(data);
},
error:function(){
// failed request; give feedback to user
}
});
}
In short, by calling the function submitToJsp(); we send an asynchronous (ajax) request to the mypage.jsp jsp with 2 parameters.
use hidden variable and then put the id into that variable.You can not pass using the code above.
<input type="hidden" name="test" value="your id" />
Then you can access like request parameter.
Your javascript code is not executed until after the JSP page has been rendered. So any java variables you want to access in your script needs to be pre-rendered as a javscript variable. After the page has been rendered, you can't execute java code in your javascript. You can't "share" variables between java code and javascript like that. Your example is probably simplified, but in this case, you could just do
var something = <%= sample.getSomethingById(4) %>
You should use hidden field :-
<input type="hidden" name="hdtest" id="idtest" value="<%=sample.getSomethingById(ID) %>" />
Now inside javascript try to access the value.
Try this code in java script :
var something = document.getElementById('idtest').value;
Hope it will help you.
Related
I'm trying to change the value on an input using javascript file called from Ajax, obviously, it's NOT Working :/
I have a page where I have:
<input type="text" id="hello">
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
},
error : function () {
}
});
in the index.php, I have:
echo "
<script>
parent.document.getElementById('hello').value = 'Please work';
</script>
";
I even tried "window.parent.docu....", still no luck.
Any way there's a way to do it via the PHP file? Thanks a bunch!!
Please note, I do NOT want to this in the callback because i don't want users to see the handling of all the variables etc etc I want all that info to be done in PHP and then when it's complete fill out the variables on the main page.
This sort of thing trips up a lot of PHP coders. PHP rendering happens on the server. By the time the page has been delivered to the user, it's just HTML and javascript; further attempts to modify the page via PHP will not work; echoing a new line of js will not append it to the document and execute it the way you're expecting it to.
Instead, you need to have your PHP script return the text you want inserted, and use javascript in the rendered page to insert it:
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
document.getElementById('hello').value = result;
},
error : function () {
}
});
You really should not proceed with this design. Use callbacks correctly and properly decouple your interface from your backend instead.
However, if you want to cut corners here, you should be able to parse the resultant HTML string (provided its validity), then insert the parsed content into the DOM which should achieve what you seem to want:
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
document.appendChild(new DOMParser(result, "text/html").getRootNode().body);
},
error : function () {
}
});
Seeing your comment about not wanting to us JavaScript because users can then see the code, and preferring it in the PHP (server side)... you can skip Ajax altogether and just put something like...
<input type="text" id="hello" value="<?php echo $variableWithData; ?>" />
... into the PHP page, and the HTML the gets sent to the client will just have something like...
<input type="text" id="hello" value="please work" />
Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?
I can provide two ways,
a.jsp,
<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>
b.jsp,
<script>
var v="xyz";
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("value="+st);
%>
Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.
To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.
simple, you can't!
JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.
I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>
You cannot do that but you can do the opposite:
In your jsp you can:
String name = "John Allepe";
request.setAttribute("CustomerName", name);
Access the variable in the js:
var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);
If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.
Other wise you can't do it.
Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.
This is for other people landing here.
First of all you need a servlet. I used a #POST request.
Now in your jsp file you have two ways to do this:
The complicated way with AJAX, in case you are new to jsp:
You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:
$(document).ready(function() {
var sendVar = "hello";
$('#domId').click(function (e)
{
$.ajax({
type: "post",
url: "/", //or whatever your url is
data: "var=" + sendVar ,
success: function(){
console.log("success: " + sendVar );
<%
String received= request.getParameter("var");
if(received == null || received.isEmpty()){
received = "some default value";
}
MyJavaClass.processJSvar(received);
%>;
}
});
});
});
The easy way just with JSP:
<form id="myform" method="post" action="http://localhost:port/index.jsp">
<input type="hidden" name="inputName" value=""/>
<%
String pg = request.getParameter("inputName");
if(pg == null || pg.isEmpty()){
pg = "some default value";
}
DatasyncMain.changeToPage(pg);
%>;
</form>
Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).
I Used a combination of the scriptlet, declaration, and expression tags...
<%!
public String st;
%>
<%
st= "<html> <script> document.writeln('abc') </script> </html>";
%>
<%=
" a " + st + " <br> "
%>
The above code is working completely fine in my case.
I have a simple input text field:
<input type="text" id="master_password" size="20" placeholder="Master Password" />
<a class="btn btn-default" id="master_submit" href="#">Submit</a>
And some javascript listening:
$(document).ready(function() {
$('#master_submit').click(function() {
alert("sometext");
});
});
The alert works, obviously. I want to store the text field (#master_password) in session[:master_pass] as I will be using it to decrypt many passwords stored in the database. I'm pretty sure I have to use some AJAX, but not familiar with it at all. What code would I replace the alert with in the js file (or view, or controller, of course) to store the data as a Ruby variable?
Assuming you're using Rails, you could use javascript to make an AJAX request to the Rails app, and then in Rails, you could set the session value.
In Javascript (jQuery):
var data = "password=" + encodeURIComponent($('#master_password').val());
$.ajax({
url: '/my_controller/action',
data: data,
type: 'post'
})
.done(function(response) {
// Do something with the response
})
.fail(function(error) {
// Do something with the error
});
And in Rails, setup a controller with the appropriate route, and in the action:
class MyController < ApplicationController
...
def action # << name whatever you like
session[:password] = params[:password]
end
...
end
First of all thanks to you all for your valuable suggestion.I got stuck one problem that is in jQuery ajax call in grails remote function call on controller.
The plug-ins installed in my project are: jQueryUi - 1.10.3, jQuery - 1.11.0.
My controller this method:
def loadamount(){...}
And for ajax call method:
def ajaxCallBalance(long id){
def userBalances=loadamount(id)
def userBalance=userBalances[0] //it returns in array
return [usreBalance:userBalance]
}
These are nothing but my database call to load user amount in his a/c that should load on page load inside user profile html page. So for that i use this:
Point 677:
<g:if test="${session.LogedUser}">
<script>
${remoteFunction(
controller:'user',
action:'ajaxCallBalance',
update:[success:'uresult',failure:'uresult'],
id:session.LogedUser.id
)}
</script>
In HTML:
<li id="uresult"><!-- Want to see hare what result either value or error it returns --></li>
In firebug console I see get this error:
SyntaxError: syntax error
<script>
jQuery.ajax({
type:'POST',
url:'/...../..../ajaxCallBalance/10000000',
success:function(data,textStatus) {jQuery('#uresult').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown)
jQuery('#uresult').html(XMLHttpRequest.responseText);
}
});
</script>
[Note:This is generated by grails ajax plugin what i have wrote is see point 677.]
Here is my Question:
Why is this $#39; appearing even though I have no space, nor any symbol. Is it a bug or my mistake?
Is there any way to handle this kind of scenario as user onLoad/(document).ready() call for such conditions. If Yes, then what I will do?
You can't just use the grails construct of ${remoteFunction...} in js directly. use ajax:
$.ajax({
type: 'POST',
url: "${createLink(action:'ajaxCallBalance', controller:'user')}",
data: { id: id },
success: function (dataCheck) {
//Do stuff
}
........
});
or use g:remoteFunction like this way
$('mydiv').onclick = <g:remoteFunction action="ajaxCallBalance" controller="user" id="${id}" />
As a novice js and jqplot programmer, I need guidance on passing an array of value from php to an external javascript for plotting (using jqplot). I am confused about the order and how html, php & external js, jqplot is called. A short sample code structure will be very helpful to follow. We may use the following sample codes as guide. Thanks
$(document).ready(function(){
var plot1 = $.jqplot ('chart1',[[3,7,9,1,4,6,8,2,5]],{title: 'Plot'});
});
Instead of the fixed data points above, I want them to dynamically loaded via an array from the following php script.
<?php
$Start_Value = $_POST['Start'];
$End_Value = $_POST['End'];
for($i=$Start_Value;$i<=$End_Value;$i+++)
$Plot_Val[$i] = $i + 2;
json_encode($Plot_Val);
?>
You have several options. Here are the 2 easiest:
Just 'paste' the array from PHP as a JavaScript global variable.
Add <script>var myData = <%= json_encode($Plot_Val); %>;</script> at the top of your page and then use myData in place of the data array.
Even better option is to use Ajax to call the PHP page from JavaScript and get the results , separating front-end and back-end code.
Best way is to use AJAX, something like this in JS:
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
Update: To get your values from a form, you cannot put form action to js, but rather use js to get the values from a form. So the form itself shouldn't do a POST request, but rather the js should take the values from a form and send the POST.
Something like this:
<form>
<input type="text" id="start">
<input type="text" id="end">
<button id="submitButton">Submit Me!</button>
</form>
JS, we will wrap the above AJAX code into a function:
function submitValues(startValue, endValue) {
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
}
$(document).on('click', '#submitButton', function(){
var start = Number($('#start').val());
var end = Number($('#end').val());
//I guess you need numbers instead of text, that's why they are wrapped inside Number()
submitValues(start, end);
});
This should work.
Keep in mind that I have no idea what your form looks like, this is just a dummy example, but it should be similar enough. You get the form values with the jQuery's .val() method and then give those values to the ajax function.