Give a javascript alert after submit JSP without refreshing the page - javascript

I am entering data into a jsp page and validating it from the database. I need to give an alert on the JSP page if the validation is false without refreshing the page as the user is forced to re-enter all the details when the page is refreshed:
My validation Method:
public boolean accountCifMismatch(String account, String custid) {
Connection conn;
int count = 0;
try {
conn = db.getDbConnection();
String sql = pr.getDBProperty().getProperty("com.crb.accountCifMismtach");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, account);
ps.setString(2, custid);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
count = rs.getInt(1);
}
DBConnection.closeConn(conn);
System.out.println(MemoryListener.getMemoryDetails());
} catch (Exception asd) {
System.out.println(asd.getMessage());
return false;
}
return count == 0;
}
My servlet call:
Fraud fmd = new Fraud();
if (!fmd.accountCifMismatch(account_no, cust_id)) {
//Continue Processing
} else {
session.setAttribute("accountcifmismtach", true);
session.setAttribute("content_page", "fraud.jsp");
}
and on fraud.jsp I call a javascript:
<script type="text/javascript">
if (${accountcifmismtach == 'true'}) {
alert("Account Number CIF Mismtach");
}
</script>
EDIT I am submitting the form:
<form id="form1" name="form1" method="post" action="do?MOD=BOK&ACT=doFindFraud">
</form>
The alert shows and then the page is refreshed, so the user has to input all the details once more. How can I show the alert without refreshing the page?

If you want to validate the Form without refreshing the Page , You need to use AJAX .
There are many ways to make ajax calls but with Java Programming Language I prefer DWR(Direct Web Remoting)Easy AJAX for java
DWR Way :
http://directwebremoting.org/dwr/documentation/index.html
Other Famous ways listed below :
JQUERY Way
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
JavaScript (No Jquery Required)
function AJAXPost(formId) {
var elem = document.getElementById(formId).elements;
var url = document.getElementById(formId).action;
var params = "";
var value;
for (var i = 0; i < elem.length; i++) {
if (elem[i].tagName == "SELECT") {
value = elem[i].options[elem[i].selectedIndex].value;
} else {
value = elem[i].value;
}
params += elem[i].name + "=" + encodeURIComponent(value) + "&";
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}

Write return false after alert and focus the required input form element in javascript.
Ex: docuemnt.getElementById('requiredInputElement').fous;

Related

Stop submitting form if user doesn't exist in Database

I am developing a code in JSP using Ajax to verify the user in DB (means there is one input box where user provides the email id then code checks whether user exists or not using ajax), if user doesn't exist on DB then user should not be able to submit the form. In below code, Ajax is working. It shows true/false according to returning from JSP user check file (user_exist_function.jsp) but I am not able to control to user to stop submitting if user doesn't exist on DB. Please help.
js
var MyApp = {};
function check() {
xmlHttp = GetXmlHttpObject()
var url = "user_exist_function.jsp";
value = document.getElementById('email1').value;
url = url + "?username=" + value;
xmlHttp.onreadystatechange = stateChanged
xmlHttp.open("GET", url, true)
xmlHttp.send(null)
}
function stateChanged() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
var showdata = xmlHttp.responseText;
document.getElementById("mydiv").innerHTML = showdata;
MyApp.status = showdata;
}
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function check_submit() {
var var1 = MyApp.status.valueOf().toLocaleString();
if (var1 == 'true') {
return false;
} else {
return true;
}
}
html
<form name="form" onsubmit="return check_submit();">
Email Id: <input type="text" name="email" id="email1" onkeyup="check();">
<font color="red">
<div id="mydiv"></div>
</font>
<input type="submit">
</form>
user_exist_function.jsp
<%#page import="java.sql.*" %>
<%#include file="Database_connectivity.jsp" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
try{
String username = request.getParameter("username").toString();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM V_USER_DATA WHERE " +
"EMAIL = ?");
ps.setString(1,username);
ResultSet res = ps.executeQuery();
if(res.next())
{
out.println("false");
}
else
{
out.println("true");
}
}catch (Exception e){
out.println(e);
}
%>
<input id="Mysubmit" type="submit">
<span id="msgNotInDB" style="display:none">You are not in the database</span>
if(res.next())
{
$("#Mysubmit").hide();
$("#msgNotInDB").show();
}
else
{
$("#Mysubmit").show();
$("#msgNotInDB").hide();
}
Note: this answer using jQuery, because any sensible attempt to use AJAX on a webpage would use jQuery (or at least a similar library). What I showed can be done without it (using document.getElementById()) but there's really not much sense in it.
UPDATE:
I noticed that I put the jQuery code in the server-side code. SO, let's expand our rewrite. This should replace all of the given Javascript:
function check()
{
$.get("user_exist_function.jsp", {username: $("email").val()},
function(data) {
if (data) {
$("#Mysubmit").show();
$("#msgNotInDB").hide();
} else {
$("#Mysubmit").hide();
$("#msgNotInDB").show();
} );
}

How to display additional info on mouseover with ajax and javascript

I have an e-commerce simulation web app for buying movies and I want a popup small window to appear when a user mouses over the movie's id and display info and give them the option to add that movie to their cart (like how Facebook displays users info when you mouseover one of your friend's names). I have a java servlet that receives the movie's id and gets the proper info from my database and sends it back to the JSP, but form there I don't know how to properly use AJAX or jquery to display the window with the proper info.
SERVLET CODE
int movie_id = Integer.parseInt((String) request.getParameter("movie_id"));
StringBuilder query = new StringBuilder("select * from movies where movies.id =");
query.append(movie_id);
// Perform the query
MySQLHandler sql_handler = new MySQLHandler( );
sql_handler.execute_query( query.toString() );
ResultSet result = sql_handler.get_result();
try {
Movie movie = createMovie(result);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(movie.getTitle());
request.setAttribute("movie", movie);
}
catch(SQLException e) {
e.printStackTrace();
}
}
JAVASCRIPT CODE
function ajaxFunction(movie_id){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
}
}
alert(movie_id);
var parameter = "movie_id=" + movie_id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
, "application/x-www-form-urlencoded") //Needed for post request for some reason. //http://www.javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml
ajaxRequest.send(parameter);
}
$.ajax({
url: 'route/to/videoinfo' + specificVideoId,
type: "POST",
contentType: "application/json ;charset=UTF-8",
}).done(function(result){
(if you rendered out the html already just do)
var containerDiv = document.getElementById("#idOfDivToFill")
containerDiv.innerHTML = result
}).fail(function(err){
console.log(err)
})
Someone let me know if this is terrible.

what causes the URL to change upon form submissions

I often seen websites with a search function and when they search for something, the web page often changes the url to something along the lines of
search.php?q="searchquery"& etc , i have a search page on my site and i use ajax to submit a form that has a search input and sends to a php page which searches through my database and returns data to a specific div on the original page via echo.
function getdata() {
var str = document.getElementById("searcb");
document.getElementById("demo").innerHTML = "You are searching for: " + str.value;
document.getElementById("searchresults").style.display="block";
if (str == "") {
document.getElementById("demo").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("searchresults").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getuser.php?q=" + str.value, true);
xmlhttp.send();
return false;
}
}
HTML
<form onsubmit="return getdata()">
<input type="search" id="searcb" name="searchBar"></br></br>
</form>
My question is what am i doing differently that causes my url to remain the same compared to a common search engine
In general the url change because a post that reload the page is performed. Your url will not change because you call make an ajax call that will not reload your corrent page .

Ajax call with ONLY javascript (no jquery)

I'm trying to do an ajax call with POST method, but the PHP only return an empty array. What am i doing wrong?
JAVASCRIPT
// ajax call
function makeRequest(){
var http_request = false;
// example data
var fileObjectInfo = 'bla';
var url = 'archivo.php';
if (window.XMLHttpRequest){
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
}else if(window.ActiveXObject){
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if (!http_request) {
console.log('Falla :( No es posible crear una instancia XMLHTTP');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.send(fileObjectInfo);
function alertContents(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
console.log(http_request.responseText);
} else {
console.log('Hubo problemas con la peticiĆ³n.');
}
}
}
}
My php only do: <?php print_r($_POST); ?> (i tried with request too), but always return an emty array. (so the call works but javascrip doesn't send the information, no?)
I get examples code from internet but never works the ajax call with POST method and i don't know why.
thank you in advance for all the help they can lend.
If You request post method you must be pass header data with request like
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", fileObjectInfo.length);
http_request.setRequestHeader("Connection", "close");
put this data before http_request.send(fileObjectInfo);
I hope this will help you
To send a POST request you need a form data object containing key value pairs for PHP to interpret post values
var fileObjectInfo = new FormData();
fileObjectInfo.append("key", "value");
fileObjectInfo.append("name", "prince");
// ajax code
http_request.send(fileObjectInfo);
In PHP then do this
echo $_POST["key"];
echo $_POST["name"];
Be sure to check if the post params exist using isset()

Use of Ajax to refresh Struts2 datatable

I have created a datatable in Struts2 and also have a feature of adding a record into this table by some action. After the record is inserted we are refreshing the page to get the table refreshed.
I had tried to use Ajax for this purpose and send the new values we have inserted to the Action class by request parameter and in the response we are getting the table refreshed.
My Ajax function is:
function reloadTable(){
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser has no AJAX Support!");
return false;
}
}
}
var elem1 = document.getElementById('host0');
var elem2 = document.getElementById('ip0');
var elemTable = document.getElementById('hostTable');
//alert(indexSelected);
//alert(document.getElementById(elem).options[indexSelected].value);
var url = "insertTable.action";
ajaxRequest.open("POST", url, true);
ajaxRequest.onreadystatechange = function()
{
try
{
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var res = ajaxRequest.responseText;
if (res)
{
//alert("hi"+res.greeting);
document.getElementById("hostTable").innerHTML = res;
//adjustTable();
}
}
}
catch (e)
{
}
};
//alert(selectedCountry);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var hostName = elem1.value;
var ipAddress = elem2.value;
//alert("AJAX CALL"+elem1.value+elem2.value);
//ajaxRequest.send("hostName="+elem1.value+"&ipAddress="+elem2.value);
ajaxRequest.send("hostName="+hostName+"&ipAddress="+ipAddress);
//ajaxRequest.send(null);
}
Content in my Struts.xml is:
<action name="insertTable" method="insertNewData" class="action.LoginAction">
<result name="success">/success.jsp</result>
</action>
Method in my action class:
public String insertNewData(){
populateList();
System.out.println("Hi"+getHostName()+getIpAddress());
userNameList.add(new UserType(hostName,ipAddress));
return SUCCESS;
}
Now I want the list populated in the actionClass method to be reflected in the table by this Ajax call. In this method I am appending the value that I am sending through parameter in the Ajax method. I can fetch the new values in the action class method but while sending the response the whole page is displayed in place of the table.
Thanks,
Sachin
After the record is inserted we are refreshing the page to get the
table refreshed.
Is it like you don't want to refresh the whole page for that. In that case I suggest you to use Struts2 Jquery Plugin. Grid showcase does exactly what you want to do.
For more examples you can visit Online Examples and can request can example if you want something more specific.

Categories

Resources