How to add ajax action to jsp page? - java

I have to add ajax action to date field. When user choose appropriate date, it should show at table all free apartment.
How to implement this at jsp page. I'm newly at JavaEE.
Here is content of page:
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%# page errorPage="error/errHandler.jsp" %>
<jsp:include page="/WEB-INF/jspf/header.jspf" />
<html>
<head>
<title>Reservation an apartment</title>
<h1 align="left">Reservation an apartment</h1>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/bookRoom">
<div class="reservation-group" align="left">
<label class="places-label">Couch places at room</label>
<span class="selections">
<select id="r_select">
<option>select</option>
<option>1 person</option>
<option>2 persons</option>
<option>3 persons</option>
<option>4 persons</option>
</select>
</span>
</div>
<br/><br/>
<div class="reservation-group" align="left">
<label>Star rating</label>
<select>
<option>select</option>
<option>2 stars</option>
<option>3 stars</option>
<option>4 stars</option>
<option>5 stars</option>
</select>
</div>
<br/><br/>
<div align="left">
<label>Check-in date</label>
<input type="date" placeholder="yy/mm/dd"/>
</div>
<br/><br/>
<div align="left">
<label>Check-out date</label>
<input type="date"/>
</div>
<br/><br/>
<div class="register-group" align="left">
<div class="selections">
<input type="reset" value="Reset" class="btn" />
<input type="submit" value="Register" class="btn" />
</div>
</div>
</form>
</body>
</html>
How does this ajax technologist works on jsp in general? Do we need to use javascript or jquery? If yes, how exactly will be right.
Looking of the page:
I want to understand this implementation. Any suggestions are appreciate.

Use onchange event as ,
<input type="date" placeholder="yy/mm/dd" onchange="sendAjax()" id="checkInDate" />
You jquery will be ,
<script type= "text/javascript">
$( document ).ready(function() {
});
function sendAjax() {
var checkInDate= $("#checkInDate").val();
//var checkOutDate= $("#checkOutDate").val();
$.ajax({
type: "POST",
url: "You URL path"
data: "checkInDate" + checkInDate,
dataType: "html",
success: function(response) {
//alert("Success : "+response);
if(response != null && response !="" && response !="null"){
//do you stuff here
}
},
error: function(e) {
alert('Error: ' + e.message);
},
});
}
</script>

This has nothing to do with the type of server-side view rendering technology you are using (in your case JSP), it's a question of having some JavaScript code react on a change in the date select box and then trigger a call to a server function that returns the available apartments given the entered date.
JQuery is JavaScript, it's a commonly used JavaScript framework. And yes, you could very well use it for this task. Just add an id to your date select box (for example "checkindate"):
<input id="checkindate" type="date" placeholder="yy/mm/dd"/>
and then use JQuery to attach code to the change event which calls your server with the selected date:
$(document).ready(function() {
$("#checkindate").change(function(event) {
var selectedDate = event.target.value;
$.get("/your/server/function?selectedDate=" + selectedDate, function(data) {
// populate list with data
}, "json");
});
});
Your server function will have to read the query parameter "selectedDate" and with that construct a list of available apartments in (for example) JSON format and return that to the client.

Use onChange event and and send the ajax call on onChange event.
You can use onClick,onblur() event too
<script>
function onDateChange(){
//Alert OnChange is Called
alert("Date Changed");
//Send ajax call
}
</script>

Related

How to properly include a jsp in another jsp

I'm making a form to add events to a list but I need to be able to see in that form the previous events from that list. I have a jsp that shows a list of events but it takes an attribute usually added by the controller when you access the list directly from the browser.
So how can I add the list jsp filling that attribute so it shows a list and not just the headers?
I have alreay included the jsp using
<jsp:include page="comp_list.jsp"></jsp:include>
And it shows the headers but as there is no attribute it shows no list. I tried adding attributes to the include like:
<jsp:include page="comp_list.jsp">
<jsp:attribute name="compensaciones">
${compensaciones}
</jsp:attribute>
</jsp:include>
But when I do it it shows an error telling me that this cannot be done.
Also tried params but that would not be the answer for me because params are treated in the controller and not in the jsp itself.
I'm just getting the header of the list which is fine, but i would like to see the list.
Edit: this is how i build the list in case you are wondering
<tbody>
<c:forEach var="comp" items="${compensaciones}">
<td>${comp.getSomething()}</td>
...
</c:forEach>
</tbody>
<jsp:include page="pagename.jsp" />
i thing you are not provide extension in your include tag
Sometimes since I've had prior experience back in the days with HTML and PHP, we simply just would include things like navigation and header for easier management.
I'm unsure for what purpose you're including JSP, but here's an example of how I've done it since I include JSP if a boolean is true.
The site that is accessed:
<div class="row">
<div class="col-lg-2">
</div>
<div class="col-lg-8">
<%
if (loggedin) {
%>
<%# include file="includes/profile.jsp" %>
<% } else {
out.println("<div><h2>You aren't logged in!</h2></div>");
}
%>
</div>
<div class="col-lg-2">
</div>
</div>
And the top and bottom of the JSP file I'm including doesn't contain things like head, title, html, body etc.
<%
User currUser = null;
currUser = (User) session.getAttribute("user");
%>
<div>
<h2>Du er logget ind, velkommen <% out.println(currUser.getUsername().toUpperCase()); %></h2> <br>
<h5>Din Saldo: <b><% if (currUser.getBalance() < 0) { out.println("<font color='red'>" + currUser.getBalance() + "</font>");} else { out.println("<font color='green'>" + currUser.getBalance() + "</font>");} %></b></h5>
<br>
<form class="form" method="post" action="#">
<h4>Oplysninger: </h4>
<h6>
For at ændre oplysninger skal du indtaste dit kodeord!
</h6>
Nuværende Kode: <input type="password" class="form-control" placeholder="kodeord" name="password" required>
<hr>
Email: <input type="text" class="form-control" value="<% out.println(currUser.getEmail()); %>" name="email"> <br>
Brugernavn: <input type="text" class="form-control" value="<% out.println(currUser.getUsername()); %>" name="username"> <br>
<input type="submit" class="btn btn-default" value="Indsend Oplysninger" />
</form>
</div>
When importing JSP into JSP, it's important to know that they will conflict if 1. Duplicate Local Variables. 2. Certain HTML tags aren't correct.
Your intended use seems very complicated to me since I'm not quite understanding it, sorry :3 but if you can't get it working consider to throw it to a session and if it's a one time use then remove it once you used it.
This is working from dacades
<%# include file="../scripts/standard_head_declaration.jsp" %>

Two forms on one page, can you prevent refresh when submitting one of two forms?

My Java/Springboot/Thymeleaf app has a page with multiple forms. One form contains a modal that pops up when you click a button, so you can attach files. When you hit submit to attach the file, it gets saved to a file on the server, but refreshes the original form and I lose my form inputs. Any way to prevent the default so it doesn't refresh causing loss of data from other form (that hasn't been submitted yet), and still submit to get the file uploaded to my server?
HTML:
<div id="modal" class="modal" data-izimodal-title="Upload a Document">
<div id="newRequiredDocForm">
<form enctype="multipart/form-data" th:action="directBind" method="post" th:object="${document}">
<div class="row">
<div class="col-xs-4 col-sm-3 text-right"><label class="modalLabel">Type:</label></div>
<div class="col-xs-4 col-sm-3 text-right">
<label class="modalLabel">File:</label>
</div>
<div class="col-xs-8 col-sm-7">
<input type="file" id="file" name="document" multiple="multiple" style="margin-right:-20px;"/>
</div>
</div>
<br/><br/>
<div style="text-align: right;"><input type="button" id="attachTheDoc" class="btn btn-docModal" value="Submit"/></div>
</form>
</div>
</div>
Controller:
#RequestMapping(value="/directBind_ajax", method=RequestMethod.POST)
public #ResponseBody Document docSend(#ModelAttribute("document") Document document, Model model, #RequestParam("file") MultipartFile file){
document.setStorage(storageService.store(file));
model.addAttribute("newDocument", document);
return document;
}
Ajax Javascript:
$('#attachTheDoc').click(function(){
var data = $('#file').val();
console.log($('#file').val());
$.ajax({
type: "POST",
data: data,
cache: false,
url: "/directBind_ajax",
success: function(data){
alert("Your files have been saved");
},
error: function(){
alert("Error - File not uploaded");
}
});
});

Use a div as a submit button in JSP Servlets

I need a way to use a div as a submit button to send a form request to a Servlet, Or is there any other way to solve my problem. "logoutbutton" is the div.
<div class="logoutbutton">
<table width="100%">
<tr>
<td width="50px"><img src="img/usericon.png" width="44" height="44" /></td>
<td><a style="font-size:12px; font-family:Verdana, Geneva, sans-serif; color:#FFF"><% out.print(session.getAttribute("userid")); %></a><br />
<a style="font-size:20px; font-family:Verdana, Geneva, sans-serif; color:#FFF">Log Out</a>
</td>
</tr>
</table>
</div>
You need to call the your servlet which handles logout action for the link. You can do it using
Logout
After doing this, you can logout from doGet method of LogoutServet
I would use jquery for this and then listening for events on DOM obejcts is a peice of cake.
$(".logoutbutton").click(function () {
window.location.href = 'logout.url';
});
or
$(".logoutbutton").click(function () {
$.post( "logout.url" );
});
That's easy, use the 'onclick' event:
<div style="cursor:pointer;" onclick="submitForm();">...</div>
On the onclick you can also use
window.location.href='LogourServletUrlPattern';
if you don't want to call a function and invoke the sevlet directly
Wrap your DIV as part of your form and submit the form on clicking on DIV
<html>
<head>
<script>
function formSubmit()
{
document.getElementById("frm1").submit();
}
</script>
</head>
<body>
<form id="frm1" action="form_action">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<div class="logoutbutton" onclick="formSubmit()">
<table width="100%">
<tr>
<td width="50px"><img src="img/usericon.png" width="44" height="44" /></td>
<td><a style="font-size:12px; font-family:Verdana, Geneva, sans-serif; color:#FFF"><% out.print(session.getAttribute("userid")); %></a><br />
<a style="font-size:20px; font-family:Verdana, Geneva, sans-serif; color:#FFF">Log Out</a>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Use jquery for achieving this with ease.
In the DOM
<div id="logout-button">Logout</div>
In javascript/jquery
$("#logout-button").click(function () {
alert("ajax call to end session");
});
Even if your not using jquery you could use the above to get a round about idea on how to achieve this.
You can use javascript to capture click event on the logoutbutton div and submit the form. Assuming you have a form with id 'myform':
<div class="logoutbutton" onclick="document.getElementById('myform').submit()">
Note that using this method the div isn't treated as a hyperlink by the browser, hence you can't do right-click-and-open-in-new-tab.
If your javascript gets complicated consider using library such as jquery.

Next and Back Button in Form with Radio Button

i want to put 10 questions from database and a timer on a html form.
questions to be displayed one by one
when i click next button next question will be shown
and when clicked back button previous question should be shown
<form name="form1" bgcolor="red" action="resultbyme.jsp" method="POST">
<div style="background-color:orange;">
<% qno=n+1;
ques=rs.getString(4);
op1=rs.getString(5);
op2=rs.getString(6);
op3=rs.getString(7);
op4=rs.getString(8);
%>
<br>Q.<%=qno%>--><%=ques%></br>
<input type="radio" name="opt<%=qno%>" value="<%=op1%>" /><%=op1%><br>
<input type="radio" name="opt" value="<%=op1%>" /><%=op2%><br>
<input type="radio" name="opt" value="<%=op1%>" /><%=op3%><br>
<input type="radio" name="opt" value="<%=op1%>" /><%=op4%><br>
<%
}
} //end for
}
catch(SQLException e)
{
out.println("erorr in sql ") ;
}
%>
<div bgcolor="blue"><input type="submit" value="submit" name="submit test" /></div>
</div>
</form>
You can load everything in different div, and show them one after another with JavaScript.
You will have a common header and which will handle you timer. your html body will dynamically change (Use ajax for this ) based on user click next or back.
Better to maintain questions numbers hidden in next and back button. So in AJAX call you can get question number and pass to server to get that specific question and. You can display it in defined span or div tag.
<div id="questionId"> My question is here </div>
inside javascript
function loadQuestion(questionNo){
$.ajax({
type: "POST",
url: 'projectName/showQuestion.action',
data: "quesionNo="+questionNo
success: function(data) {
document.getElementById('questionId').innerHTML =data;
}
});
}
This is just a guide and you change thing to suit your approach

Getting the ID from a jQuery Autocomplete UI Box into a form on a JSP

I'm using JSP and jQuery Autocomplete UI.
I'm trying to pass the 'value' of the selected element in my autocomplete box into a form as a hidden value on my JSP.
Here is my script:
<script>
$(function() {
$("#search").autocomplete({
source: "list.jsp",
dataType: "json",
select: function (event, ui) {
$("#userId").val(ui.item.value);
return false;
}
});
});
</script>
Here is my form:
<form method="GET" action="view">
<div class="autocomplete">
<p>Search: <input id="search"></p>
</div>
<input type="hidden" name="userId" value="<%request.getParameter("userId");%>"/>
</form>
The autocomplete box works great but I can't seem to get a handle on the select element id!
Any help would be greatly appreciated... thanks in advance!
Use the following code to set the value of the hidden variable
// use <%= %>
<input type="hidden" name="userId" value="<%=request.getParameter("userId")%>"/>
You have used a scriptlet directly. Probably that is what is causing the problem.
Ok, I have solved the issue now.
I should have been using #userId as follows...
<input type="hidden" name="userId" id="userId" />
Where id="userId" references the #userId.

Categories