This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 5 years ago.
I have a dropdown box in JSP, listing a Java object (accessing the object through the MVC controller's addAttribute). Now, on selection of an option from the dropdown box, I would like to display the selected employee's other details (example - ${employee.employeeCV}, ${employee.employeeName}) in a div. I have a JavaScript function for that (displayCV()). But I am not sure how to do this.
JSP -
<c:forEach items="${employees}" var="employee">
<option value="${employee.id}" onclick="displayCV();">
${employee.employeeName}
</option>
</c:forEach>
<b>CV:</b>
JavaScript
function displayCV() {
var valueSelected = $('#employeeList').val();
var div = $('#candidateDiv');
}
How can I do this?
You can't access Java classes directly from JavaScript. You have to use some kind of web service communication between the JavaScript (client) and Java (server). You can make use of the onchange event which will send a request to the server to return XML/JSON which you can parse to get the data (I see you're using jQuery, and it has parseJSON method already) and update the corresponding node in the DOM.
Another easier way, though, that is not multi-user friendly (because it can't detect updates) is to "convert" the Java object to JavaScript and update the data using that object (still using onchange). Something like:
// This is JavaScript code written in the JSP
var employees = {
<c:forEach items="${employees}" var="employee">
"${employee.id}": {
name:"${employee.employeeName}",
cv:"${employee.employeeCV}",
},
</c:forEach>
}
Now when JSP parses this, it would generate, for instance:
var employees = {
"1": {
name:"foo",
cv:"cv1",
},
"2": {
name:"bar",
cv:"cv2",
},
}
Meta of what LeleDumbo said here already:
First, you must understand that JSP is a server-side view technology, whereas JavaScript typically runs on the client (browser).
Now, how you solve the problem in hand. So, you can make an Ajax request from your JavaScript code, which will fetch you the data in JSON/XML format. Then, you can present that data in the browser using JavaScript.
Further reading: jQuery Ajax API and code samnple snippets
Call the function on the onchange event of select instead of onclick of options. And use:
document.getElementById('GrdDamagedstock_tplRowEdit_ctl00_cmbFromBin').options[ele.options.selectedIndex].innerHTML;
to get the selected value.
Related
<%!
public void runJavaMethod(int id)
{
%>
<%
try{
String icd = request.getParameter("icd");
String inm = request.getParameter("inm");
String istk = request.getParameter("istock");
String sstk = request.getParameter("sstock");
String upr = request.getParameter("uprice");
String spr = request.getParameter("sprice");
r = s.executeQuery("select * from itemsyncdata");
while(r.next())
{
s.executeUpdate("update itemsyncdata set itemcode='"+icd+"',itemname='"+inm+"',instock='"+istk+"',storestock='"+sstk+"',unitprice='"+upr+"',storeprice='"+spr+"' where id='"+a+"'");
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<%!} %>
And I am Calling Function from html like
<input type="submit" id="btnSync" value="Sync" class="button" name="Sync" onclick="<%runJavaMethod(r.getInt(1));%>"/>
So We want runJavaMethod Parameter.
onclick="<%runJavaMethod(r.getInt(1));%>"/>
HTML/Javascript Plays on client side and JSP/Java plays on server side.
Simply you can't. You might misunderstand that JSP and HTML/JavaScript existed on same document. Yes but JSP part compiles on server side itself comes to client.
What you can do is you have to make a server request. Most probably look at Ajax requests.
You are trying to mix up two languages i.e., Java and Javascript/html together i.e., onclick is a Javascript event and you can't call runJavaMethod from Javascript.
In simple words, you can't directly call a Java method (present inside the scriptlet) using Javascript because all of your JSP code produces (becomes) html when it is loaded from the server.
So, if you have to fix the issue, upon onclick, you need to call an URL which hits a servlet/controller method on the server to do the job (i.e., executes the business logic).
One more important point is that Scriptlets are legacy code and I strongly suggest not use them to generate or manage the html content, rather use JSTL so that there will be a clear separation between the concerns (i.e., business logic and user interface requirements).
Also, I strongly suggest you read the JSP best practices from here and follow them.
You are mixing to two different things. JSP is server side code and it's rendered response is the HTML that is send back to the browser.Javascript is pure client side in your case.
If you really want invoke a server side processing than create a simple Java script function with Ajax call and get response back which u can use it.
I suggest send all the logic of JSP in backend class not a good practice to put in the jsp. JSP is ideally for UI design.
This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 5 years ago.
I want to read a jstl variable in a javascript function.
JS code submits a form.
$("#userSubmit").on('submit', function () {
document.getElementById("userForm").submit();
});
So in server code -
request.setAttribute("userId", 435);
and after the page is loaded -> in the javascript code -
$("#textBoxInp").keyup(function() {
// I want to access the userId here.
// in html code i can acccess it using JSTL syntax ${userId}
});
Just write the Expression Language directly in your JavaScript code:
$("#textBoxInp").keyup(function() {
var userId = '${userId}';
});
Note that this won't work if the JavaScript code is placed in a external file and is invoked in the JSP. In this case, you may refer to one of the four ways that BalusC explain here: Mixing JSF EL in a Javascript file (he explains five, but one of them is JSF specific).
One way is as suggested by Mendoza, but it will not work in case of having separate Javascript file.
in that case, another way is adding hidden field in JSP page, and reading same from Javascript.
JSP code:
<input type="hidden" id="xID" name="x" value="${myAttribute}">
JS code:
var myAtt = document.getElementById("xID").value;
If you want to access jstl variable in a javascript script function, you won't be able to access them directly. Here's a roundabout way(easy to implement) to do it.
In the HTML code have a paragraph with the required variable.
<p id = "var" disabled = "disabled">${variable}</p>
Access the variable using .innerHTML inside the JavaScript function.
function myFunction() {
var jstl_var = document.getElementById("var").innerHTML;
}
totalClients is jstl variable and to read in javascript block please see below
<script type="text/javascript">
$(document).ready(function() {
var tc = "<c:out value='${totalClients}'/>";
});
In my JSP page I have DIV.
<div id="100">
ALI
</div>
When I click on this DIV...
$("#100").click(function(){
});
...I need to send the value of the id 100, to a servlet, so that the servlet makes some database java codes, and returns for example, either 1 or 0. How can I do that? and is this the proper way?
Using Ajax, you should call your server using a URL similar to this:
http://localhot:8080/youAppContext/yourServer?id=100
Then, in the servler side, you should retrieve the value that will be in the request with the name "id"
There are out there many tool as jQuery that can help you to do the Ajax petition.
Edited
Well, here you can find a very simple Ajax example using jQuery. In the example, instead call a file (test1.txt) you should invoke a URL (as I described above). Of course, you will need to write some JS code to build your URL (where id be a variable). Once task is done in servlet side, you can return whatever, for example: "done" and display or not this information the HTML as it is done in the example.
Take a look to this Web, there are many links that can help you.
get the value using
var value = $("#100").html();
and pass it to servlet using AJAX
I'm using Spring MVC for my web application. I'm implementing the file upload functionality. Following the tutorial, I was able to send the uploaded file to server through submit action of input type of "file". Then I parsed the uploaded xls file at server side and need to send parsed data (3 lists of custom objects) back to the same form to display. I sent the data back through ModelAttribute.
However, my problem now is that on the client side, I need to use those lists of custom objects in my javascript, but I can only retrieve each field of the custom objects through jstl tag library but I cannot get those custom objects in my javascript where I need them for other logic implementation.
Then I have tried an Ajax file upload plug-in because ajax call can return JSON response which objects can be used in Javascript. But cannot get the plug-in work properly.
I have been stuck on this problem for several days>.< Can anybody help on this? Either a solution on using ModelAttribute in Javascript or a Ajax call solution is ok. Thank you very much!!!
Is there any reason why you can't simply "flatten" your model objects into HTML and then access them from Javascript using the DOM API?
You said you return 3 lists of custom objects. So how about for each list, you build up a (hidden) HTML table, for example if you have a list of Person objects in a ModelAttribute called people:
<table id="people-table">
<c:forEach var="person" items="${people}">
<tr id="${person.id}>
<td class="person-name">${person.name}</td>
<td class="person-age">${person.age}</td>
<td class="person-height">${person.height}</td>
</tr>
</c:forEach>
</table>
Now in your Javascript, you iterate over the rows in people-table, doing whatever you need to do - for example using jQuery:
$("#people-table tr").each(
var personId = $(this).attr("id");
var personName = $(this).find("td.person-name").text();
// etc, etc
// Do something with these as required
);
It's possibly not the most elegant solution but it's easy to debug at least - you can always just inspect the table with Firebug etc to see if the data is correct, and from there you'll know whether to continue debugging the server-side or in the Javascript.
I am using jQuery and a Java based backend system. I am a newbie with jQuery / AJAX and I want to do a first call.
I have this kind of HTML list:
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
</ul>
This content should be fetched from the backend system. How can I do this? Are there any tutorials? If it is one value, it is clear to me, I can tell for example a text input field that the values should be the result of the AJAX call.
But what about such a HTML list? How should I prepare the JSON message in the backend system, how to handle in the frontend system?
Best Regards
In such cases it's best to render some javascript server-side and use jQuery getScript function. So you would do something like (it's a pseudo-code, you should adapt it for your Java backend):
s = escape_javascript(render_new_list());
return "$('#mylist').html(" + s + ");";
You could also render only the list and at client side do:
$.get(url, function (data) {
$('#mylist').html($(data));
}, 'text');
If you really want to use JSON then something like this should work:
$.getJSON(url, function(data) {
var l = $('#mylist').empty();
$.each(data, function(index, value) {
l.append($('<li>' + value + '</li>'));
});
});
Assuming you send list of values you want displayed (["test1", "test2"] for example).