I'm planning to use AJAX to trigger a java servlet method which checks whether an email is already in our system or not. Then when this has completed, if the email is not in our system it will dsiplay an overlay to allow the user to accept the T&Cs, if it is already in the system it will prompt them otherwise.
Being new to AJAX and that though I am confused as to how this done/fail/always stuff works. How can I trigger this emailvalidation method, and how do I then define whether it was successful or not?
You need to the following code to validate email using AJAX:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function emailCheck(){
var email = document.getElementById('email').value;
var xmlhttp=new XMLHttpRequest();
var params = "email="+email;
xmlhttp.open("POST","emailcheck.jsp",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText == '0'){
document.getElementById('msg').innerHTML='Email already exists.';
}
else{
document.getElementById('msg').innerHTML='Email valid.';
document.getElementById('tnc').style.display='block';
}
}
}
xmlhttp.send(params);
}
</script>
</head>
<body>
<form>
Email: <input type="email" name="email" id="email" onblur="emailCheck()" required><div id="msg"></div>
<br>
<div id="tnc" style="display: none;">
<!-- T&C here -->
</div>
</form>
</body>
</html>
The onblur event will call emailCheck() function, which contains the AJAX code to perform the required task. Also note that the email is being sent using POST method.
Your emailcheck.jsp should simply output(or print) 0 if the email already exists.
Related
I have a .jsp file of a basic chat with a bot, the page is designed as a div that should hold the messages that outcome or income from a form.
The form has one input line that should hold the message.
I want to call a java function that's in a different .java file from the div only after the form is submited
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b>
<%
if (ctx.isLoggedIn()) //if there is someone in the current session
{
String name = ctx.getName(); // puts the name in the page
out.write(name); // same as last row
}
%></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox" style="overflow-y: scroll;">
<%
//the place I want to call the function
%>
</div>
<form name="message" action="#" method="post">
<input name="usermsg" type="text" id="usermsg" size="63" oninput="buttonEnabled()"/>
<input name="submitmsg" type="submit" id="submitmsg"/>
</form> <!-- the form that is served -->
</div>
ctx is defined as an object from a class I created
Context ctx = new Context(pageContext);
I tried to call the function like this-
<%
if(request.getParameter("usermsg").toString().length() > 0)// not empty
out.write(ctx.handleMessages());
%>
but It didn't work for some reason.
the function handleMessages() has a queue that contains all of the messages from the server and from the client and returns a String that is already build as an HTML code-
returnedMsg += "<b>"+message.getUser()+"</b> - <a style='color:gray;'>"+message.getTime()+"</a>";
returnedMsg += "<br>";
returnedMsg += "<a>"+msg.getText()+"</a>";
returnedMsg += "<hr>";
So every chat message should look like that-
It would really help me if someone knows how to call handleMessages() from that div when the form is submited.
Thank's ahead.
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>
I am trying to find a way to invoke a piece of java code within the JSP using HTML form
<form method="get" action="invokeMe()">
<input type="submit" value="click to submit" />
</form>
<%
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
the above code is within the JSP. I want this run the scriptlet upon submit
I know the code looks very bad, but I just want to grasp the concept... and how to go about it.
thanks
You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.
<form method="get" action="invokeMe()" id="submit">
<input type="submit" value="click to submit" />
</form>
<script>
$(document).ready(function() {
$("#submit").submit(function(event) {
$.ajax({
type : "POST",
url : "your servlet here(for example: DeleteUser)",
data : "id=" + id,
success : function() {
alert("message");
}
});
$('#submit').submit(); // if you want to submit form
});
});
</script>
Sorry,not possible.
Jsp lies on server side and html plays on client side unless without making a request you cannot do this :)
you cannot write a java method in scriptlet. Because at compilation time code in scriptlet becomes part of service method. Hence method within a method is wrong.
How ever you can write java methods within init tag and can call from scriptlet like below code.
<form method="get" action="">
<input type="submit" value="click to submit" />
</form>
<%
invokeMe();
%>
<%!
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
Not possible.
When the form is submitted, it sends a request to the server. You have 2 options:
Have the server perform the desired action when the it receives the request sent by the form
or
Use Javascript to perform the desired action on the client:
<form name="frm1" action="submit" onsubmit="invokeMe()"
...
</form>
<script>
function invokeMe()
{
alert("He invoked me. I am happy!")
}
</script>
You can't do this since JSP rendering happens on server-side and client would never receive the Java code (ie. the invokeMe() function) in the returned HTML. It wouldn't know what to do with Java code at runtime, anyway!
What's more, <form> tag doesn't invoke functions, it sends an HTTP form to the URL specified in action attribute.
I want to send the url of current page to the servlet without refreshing or reloading the page. here is the code-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Action Onclick </title>
<!-- <script>
$('#contactForm').submit(function () {
alert('sdafjb');
return false;
});
</script>-->
</head>
<body>
<form id="contactForm" >
<fieldset>
<label for="Name">Name</label>
<input id="contactName" type="text" />
</fieldset>
<fieldset>
<label for="Email">Email</label>
<input id="contactEmail" type="text" />
</fieldset>
<fieldset class="noHeight">
<textarea id="contactMessage" cols="20"></textarea>
submit
</fieldset>
</form>
<small id="messageSent">Your message has been sent.</small>
</body>
My servlet's name is scriptservlet. Please help me...
AJAX was built for communicating with a server without reloading or changing the current page in the browser. You should be able to just create an AJAX call to your server and send your server whatever data you want without affecting the current page.
Under normal circumstances, AJAX calls are restricted to "same origin" which means you can only communicate with a server on the same domain as the current web page so you would also have to make sure that you satisfy this security restriction.
Do an ajax call to the servlet and pass the Url of current page by doing (request.getRequestUri()) to the servlet.
var requestUri = '<% request.getRequestUri()%>';
var hostname = location.host;
$.ajax({
type: "POST",
url: "/scriptServlet",
data: { "host": hostname, "uri": requestUri }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Please note, syntax might not be correct but u have to make a ajax callt o achieve the result.
This is possible by sending back the appropriate response code (204 I guess) back to the client from the server (servlet). This way even though the request is submitted the page is not refreshed / reloaded.
You could use a hidden field in your form.
<input type="hidden" name="currentPage" value="<%=request.getRequestURL()%>">
I want a loading gif image to appear while processing a servlet. What I do is that before processing the form, I call a JSP which contains an animated gif with a loading image. From this JSP, I send a redirect to the servlet which processes the form.
This only works well in Chrome and in Explorer, but in Firefox the image stops moving.
The action of my form is a JSP which contains the loading image and for submiting the form I have the following code:
var form = document.getElementById('reporteEstadisticoAnualArticulo');
var win = window.open("", "reporte","width=1002, height=700,location=0, menubar=0, scrollbars=1, status=1,resizable=0");
form.target = "reporte";
form.submit();
The JSP contains the following code:
<html>
<head>
<link type="text/css" href="css/Preloader.css" rel="stylesheet" />
<script type="text/javascript">
function retraso(){
var vars = getUrlVars();
var location = document.getElementById("url").value;
window.location = location+"?"+vars ;
cargarImagen();
}
function cargarImagen() {
document.getElementById("cargando").src = "images/Cargando.gif";
return false;
}
</script>
</head>
<body onload="setTimeout('retraso()',500)">
<div align="center" class="Preloader1">
<label style="font-weight: bold; font-family: arial;">Cargando Reporte</label> <br /><br />
<img id="cargando" alt="LogoNatura" src="images/Cargando.gif">
<br /><br />
<img alt="LogoNatura" src="images/logo.png">
</div>
<input type="hidden" value="<%= request.getParameter("url") %>" id="url" />
</body>
</html>
I've tried a lot of things to avoid the image to stop moving, but I haven't found a good answer. If anyone could help, I would be pleased.
This doesn't work with iframes either. Any ideas?
I faced exactly the same issue earlier. And I fixed using IFrames.
First create a HTML file and insert the image there (loading icon). Now using IFrame just refer that file. It works fine in Firefox too. What I did is, if it IE browser, I just replaced the IFrame with image directly.
<td id="tdImgLoad">
<iframe style="height:50px;text-align:right;width:225px" scrolling="no" frameborder="0" src="web/loading.htm" id="imgLoad"> </iframe>
</td>
<script>
if(isIE())
{
getElement ("tdImgLoad").innerHTML ="<img src='images/loading.gif'>";
}
</script>
I already solved my problem. What I did is that I used ajax instead and now my jsp looks as follows:
<html>
<head>
<link type="text/css" href="css/Preloader.css" rel="stylesheet" />
<script type="text/javascript" src="js/acciones.js"></script>
</head>
<body onload="retraso()">
<div id ="reporte">
<div align="center" class="Preloader1" id="loading">
<label style="font-weight: bold; font-family: arial;">Cargando Reporte</label> <br /><br />
<img id='cargando' alt='LogoNatura' src='images/Cargando.gif'>
<br /><br />
<img alt="LogoNatura" src="images/logo.png">
</div>
<input type="hidden" value="<%= request.getParameter("url") %>" id="url" />
</div>
</body>
</html>
An my javascript file acciones.js contains the following function:
function retraso(){
var x = document.getElementById("reporte");
var content = x.innerHTML;
var vars = getUrlVars();
var location = document.getElementById("url").value;
var url = location+"?"+vars ;
xmlhttp = GetXmlHttpObject();
if (!xmlhttp) {
alert ("Browser does not support HTTP Request");
return;
}
var xml = xmlhttp;
xmlhttp.onreadystatechange = function () {
if (xml.readyState == 4) {
x.innerHTML = xml.responseText;
} else {
x.innerHTML = content;
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
return true;
}
I faced exactly the same issue earlier. And I fixed using setTimeout function!
Of course, ajax could also works well, but what I use is $("#form").submit() instead of ajax, which means that submit is synchronous with the gif image loading process. I think this problem may be due to Firefox's thread process bug(just one suspect). My solution is like the following code:
$.blockUI({ message: $("#loading").html() });
setTimeout(function(){
$("#form").submit();
},1);
Just like the code tells, let form's submit do not interfere with gif loading process and then problem solved!
Thanks for your attention!
I ran into this same issue and solved it by using a variation of the answer given by #Zhl. Instead of wrapping the form submit in a setTimeout call, I wrapped the UI update for the animated gif with a setTimeout. This saved me having to worry about the form submit details which in my case needed to call a server side method (ASP.NET).
<form id="myForm">
<button onclick="myPreSubmitFunction()">Do Stuff</button>
<img id="loading" />
</form>
<script>
function myPreSubmitFunction() {
setTimeout(function () {
//do UI update here which adds gif
document.getElementById("loading").src = "loading.gif";
}, 0);
//submit to come after the UI update
}
</script>
This prevents the gif animation being stopped by the action of the form being submitted in Firefox. As to how running a line of code via setTimeout might make a difference, this SO post is a worthwhile read.