Username availability checking using Ajax in JSP and stopping form submission - ajax

I am new to ajax and I am trying to create a gmail type username availability check by using Ajax and JavaScript in JSP.
My code works well for username availability check but I am not able to stop the form submission when a username is not available.
For checking username availability I used onkeyup() which checks each character, but for preventing the form submission I used onsubmit() in form tag.
For execution flow check I used alert statements in this code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return formValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>

Ajax is asynchronous so your call to returnFunction , need not return the correct flag, it will return false always as most probably success function will be triggered only after method is completed(onresponse).
So you need to ensure that response of Ajax cal is recieved using a completed boolean, and continuously checking it until it is true.
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
var completed = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
returnFunction(username);
while(!completed) {
//wait for ajax response
}
if(flag)
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>

<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
var flag = new Boolean(false);
function returnFunction(str)
{
alert("1");
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
document.f1.submit();
}
else{
alert("caught flage:false");
alert("Username chossen by u is already taken.Please choose different Username");
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" >
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>
make changes like this it will work .if any prob let be know.

<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function getXMLHttpRequest(){
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
};
function usernameValidation(str)
{
if (str.length==0)
{
document.getElementById("uname").innerHTML="should not be empty";
return false;
}
else if(str.length<=4)
{
document.getElementById("uname").innerHTML="need more than 4 charachers";
return false;
}
else{
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange =function()
{
if (xmlHttpRequest.readyState < 4 && xmlHttpRequest.readyState > 0)
{
document.getElementById("uname").innerHTML = "<img src='images/load.gif' alt='checking...' width=16 height=16/>";
}
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
if(xmlHttpRequest.responseText=="available")
{
document.getElementById("uname").innerHTML = "<img src='images/ok.png' alt='username available' width=16 height=16/>";
document.getElementById("uname1").innerHTML = ".";
}
else
{
document.getElementById("uname").innerHTML = "username not available";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
};
function userSubmitValidation(){
var msg = document.getElementById("uname1").innerHTML;
if(msg=='.'){
return true;
}
else{
return false;
}
};
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return userSubmitValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="usernameValidation(this.value)" onblur="usernameValidation(this.value)"></div>
<span id="uname" style="color: red"></span><span id="uname1" style="color: white"></span>
<input type="submit" value="register">
</form>
</body>
</html>

i am new at ajax too and i am kind of trying to do the same thing as you are doing. I have successfully checked the username availability using ajax and jsp. Then the thing i stuck at that even if a username is not available the page still submit after clicking submit button. Then I used javascript to solve this problem. I compared the returned text with another text declared before. If check successful then it will go to next page otherwise not. For details please check this page->"Ajax based username availablity checking and then generating some username to use in jsp". There check out the sample.jsp code. In that code a i did the checking part in the function named "conditions()". In that function the variable "checkvalue" hold the returned text which is generated by availability check. Then i compare it with the text "available". If matches then the page will submit other wise not. I am not sure is this what you wanted to know or not and if it is then my answer helps you or not. Thank you and good luck..

Related

ERR_NAME_NOT_RESOLVED in OpenWeather Api Call

I'm putting together my first Api project and I'm using OpenWeather to request conditions for a city. When I run my code, I get "ERR_NAME_NOT_RESOLVED." I've checked and rechecked my URL formatting and I'm not getting any errors when running my code. Could anyone point me in the right direction?
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script defer src="./js/script.js"></script>
<title>Weatherd</title>
</head>
<body>
<h1>Weatherd</h1>
<form>
<input type="text" placeholder="Search by city"/>
<input type="submit" value="Search"/>
</form>
<main>
<p>Weather for</p>
<p id="weatherFor"></p>
<p>Temperature: </p>
<p id ="temp"></p>
<p>Currently feels like: </p>
<p id="feelsLike"></p>
<p>Conditions: </p>
<p id="desc"></p>
</main>
</body>
</html>
My JS
const $weatherFor = $('#weatherFor');
const $temp = $('#temp');
const $feelsLike = $('#feelsLike');
const $desc = $('#desc');
const $input = $('input[type="text"]');
let weatherData, userInput;
$('form').on('submit', handleGetData);
function handleGetData(event) {
event.preventDefault();
userInput = $input.val();
$.ajax({
url: 'https://www.api.openweathermap.org/data/2.5/weather?q='+userInput+'&APPID=15ff99dd07f18bda25869ab24d06891e'
}).then(
(data) => {
weatherData = data;
render();
},
(error) => {
console.log('bad request', error);
}
);
}
function render() {
$weatherFor.text(weatherData.weatherFor);
$temp.text(weatherData.temp);
$feelsLike.text(weatherData.feelsLike);
$desc.text(weatherData.desc);
}
It's been a while since the question was asked, but given the amount of visits this question has had so far, this answer might help someone.
const url = "api_url_here";
const result = await axios
.get(url)
.then((res) => {
const { status } = res;
return status && status == 200
? { ...res.data, status: 200 } // return data + status 200
: { status: 400 }; // create and return status 400 on error
})
.catch((err) => {
return { status: 400 }; // create and return status 400 on error
});
// work with the returned status
if(result.status == 200) {
// success
} else {
// error
}
I used axios, but the idea is very much transferable to Fetch Api or Ajax.

Onchange() for AJAX

I am trying to display the onchange value of a textbox using ajax. My code is as follows :
ajaxquery.php
<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
//fuction to return the xml http object
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">
<form style="text-align:center" method="post" action="" name="form1">
<p>Country : <input type="text" name="country" onChange="getCurrencyCode('code.php?country='+this.value)">
</form>
</body>
</html>
code.php
<?php
$country=$_REQUEST['country'];
echo $country;
?>
The value is not displaying. Where am I going wrong?
P.s. I am completely new to ajax and have no knowledge about it. Appreciate any help :)
<p>Country : <input type="text" name="country" onblur="getCurrencyCode('code.php?country='+this.value)">
<p>Country Code : <input type="text" name="cur_code" id='cur_code' ">
Changed the onchange function to onblur and added another input type. It is working perfectly now!

Dropdown using Ajax

I wrote the below code; when I select India/America in the dropdown related text files with some contents, has to be read and displayed inside a div element, but am getting an error in the line xhr.send()
can anyone explain why??
<html>
<head>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>

Ajax ready state not stuck on 1

after searching the internet I was unable to find an answer as to why my AJAX code is not working. My assignment is to retrieve a text file and display it to the browser using AJAX but the ready state stops at 1. an example file is canada.txt and is located in the directory http://157.201.194.254/~ercanbracks. The .html and .js files are below:
HTML file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>AJAX</title>
<link rel="stylesheet" type="text/css" href="assign09.css" />
<script type="text/javascript" src="assign09.js"></script>
</head>
<body>
<h1>Ten Largest Cities</h1>
<h3>Select a Country:</h3>
<form action="">
<select id="country">
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
<option value="russia">Russia</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit"
onclick="makeRequest(document.getElementById('country').value)" />
<div id="error"> </div>
</form>
<h3>Cities:</h3>
<div id="cities">
<pre>
City Population
------------------ ---------------
<span id="cityList"></span>
</pre>
</div>
</body>
</html>
.js file:
var httpRequest;
var countryOption;
function makeRequest(option)
{
countryOption = option;
if (window.XMLHttpRequest) // Modern Browsers
{
httpRequest = new XMLHttpRequest();
}
else // older IE browsers
{
try
{
httpRequest = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e)
{
try
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('ERROR - Unable to make XMLHttpRequest');
}
}
}
if (!httpRequest)
{
alert('ERROR: httpRequest failed -- try a different browser');
return false;
}
else
{
var url = "http://157.201.194.254/~ercanbracks/" + option + ".txt";
alert('Ready State = ' + httpRequest.readyState);
httpRequest.onreadystatechange = getCities;
httpRequest.open("GET", url, true)
httpRequest.send(null);
}
}
function getCities()
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.readyState == 4)
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.status == 200)
{
var response = httpRequest.responseText;
document.getElementById("cities").innerHTML = response;
}
else
{
alert('problem with request');
alert('Ready State = ' + httpRequest.statusText);
}
}
}

Ajax Code To Display Data

I wrote this code in javascript to disply information in this page (Normal_Info.php),
but unfortunately it did not work. If anyone can help me I will be grateful
<html>
<head>
<script language="javascript">
function ajaxFunction()
{
return window.XMLHttpRequest ?
new window.XMLHttpRequest :
new ActiveXObject("Microsoft.XMLHTTP");
}
function Go_there()
{
var httpObj = ajaxFunction();
httpObj.open("GET","Normal_Info.php", true);
httpObj.send();
httpObj.onreadystatechange = ChangedState()
{
if (httpObj.readyState == 4 && httpObj.status == 200)
{
document.getElementById("result").innerHTML=httpObj.responseText;
}
}
}
</script>
</head>
<body>
<form id=ff>
<input type=button value=Hi OnClick=Go_there() />
</form>
<div id=result>
</div>
</body>
</html>
i suggest using jquery http://jquery.com/
<script src="jquery.js"></script>
<script language="javascript">
$('#ff').submit(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('#result').html(data);
// alert('Load was performed.');
}
});
});
</script>
no need to click event

Resources