I am trying to check username available or not when a user tries to create his account. when a user types it's username there should be an instant check that username is available or not and it will show a message in just below the username box.
I was tried to achieve it by calling an Ajax but not able to understand what to return basically and how will it work, actually I am very new in Struts 2 , I am able to check the username but did not under what to return.
My Ajax Call
<script>
$(document).ready(function () {
$("input").blur(function () {
var input = $(this).val();
alert(input);
$.ajax({
url:'checkUsername',
method:"POST",
data:{username:input},
success:function(data)
{
if(data!='0'){
$('#availability').html('<span>not available</span>')
$('#update').attr("disabled",true);
}
else{
$('#availability').html('<span>available</span>')
$('#update').attr("disabled",false);
}
}
})
});
});
</script>
checkUsername Action
public String checkUsername() {
try {
setCtr(admin.checkUsername(username));
if (ctr > 0) {
System.out.println(ctr);
setNoData(false);
} else {
setNoData(true);
}
} catch (Exception e) {
e.printStackTrace();
}
return "CHECKUSER";
}
method to check username in dao
public int checkUsername(String username) throws Exception {
ResultSet rs = null;
Connection con = null;
try {
con = ConnectionManager.getConnection();
System.out.println(username);
String sql = "SELECT * FROM userinfo WHERE username =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, username);
rs = ps.executeQuery();
if (rs.next()) {
return 1;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
}
}
return 0;
}
}
This method in dao is able to check the username but what to return in that ajax data which i am trying to check that the if rows > 0 it should print not available. How to return and how to check?
struts.xml
<action name="checkUsername" class="com.redress.actions.AdminAction" method = "checkUsername"> </action>
Can anyone please correct me, how to achieve this?