Stop submitting form if user doesn't exist in Database - javascript

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();
} );
}

Related

Send radio button data (value) to PHP via Ajax

In the below JavaScript, I am unable to send radio button data to PHP. Example: if radio button "Mother" is selected, the selected value of "Mother" should be send through ajax. But my problem is that I am unable to send the selected radio button value from ajax. I Google'd it, but I am unable to solve it. Can you share the code for solving this problem.
This is the JavaScript code:
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax() {
var test = $("#txtUsername").val();
var test2 = $("#txtPassword").val();
if(test=='')
{
alert("Please Enter Register Number");
}
else if(test2=='')
{
alert("Please Enter Date Of Birth");
}
else
{
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
**// iam using this For Validation to send data to different urls based on selection**
var game1 = $('input[type="radio"]:checked').val();
if (game1 === "Mother") {
var url = 'http://localhost:9999/check.php';
}
else if (game1 === "Father") {
alert('Father');
}
else {
HttPRequest = false;
alert('select 1');
}
**this is Where ima stucked**
var pmeters = "tUsername=" + encodeURI( document.getElementById("txtUsername").value) +
"&tPassword=" + encodeURI( document.getElementById("txtPassword").value );
"&game=" + $('input[type="radio"]:checked').val();
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "Now is Loading...";
}
if(HttPRequest.readyState == 4) // Return Request
{
if(HttPRequest.responseText == 'Y')
{
window.location = 'success.html';
}
else if (HttPRequest.responseText == 'z')
{
document.getElementById("mySpan").innerHTML = "";
window.alert("bad registernumber or dob");
}
else if (HttPRequest.responseText == 'b')
{
document.getElementById("mySpan").innerHTML = "";
window.alert("userexist");
}
}
}
}
}
</script>
This is html code
<br/>
<input type="radio" name="game" value="Mother">Mother
<br />
<input type="radio" name="game" value="Father">Father
<br />
<input type="radio" name="game" value="Self">Self
<br />
<input type="radio" name="game" value="Other">Other
<br />
</table>
<br>
<input name="btnLogin" type="button" id="btnLogin" OnClick="JavaScript:doCallAjax();" value="Login">
First I would suggest you to use jQuery, because it is really simplier and better.
Then you can use the following code to post the checkbox/radio value:
$("#game").val()
Here you can find the really simple syntax for Ajax with jQuery.
Please remove $('input[type="radio"]:checked').val() and replace with a var game. Before that please use below code to get value of checked radio button in var game.
var elements = document.getElementsByName("game");
var game;
for(var i = 0; i < elements.length; i++ ){
if(elements[i].checked){
game = elements[i].value;
}
}
So now your code will look like
var pmeters = "tUsername=" + encodeURI( document.getElementById("txtUsername").value) +
"&tPassword=" + encodeURI( document.getElementById("txtPassword").value );
"&game=" + game;

auto Submit form on max length, - add a java script code for existing one

i am trying to auto submit form when the input reaches 7 characters. i have tried few java script codes, but it is spoiling my script functioning.
can any one please help me in this.....
<script type="text/javascript">
var url = "GetCustomerData.php?id="; // The server-side script
function handleHttpResponse() {
if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('divCustomerInfo').innerHTML = results;
}
}
}
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
<form id="form_home">
<p>Enter customer ID number to retrieve information:</p>
<p>Customer ID: <input type="text" maxlength="7" id="txtCustomerId" value="" /></p>
<p><input type="submit" value="Submit" onclick="requestCustomerInfo()" /></p>
</form>
<div id="divCustomerInfo"></div>
Here is the code that will submit the form when the text box reaches 7 chars:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
document.getElementById('form_home').submit();
}
});
Here is a demo of it working:
http://jsfiddle.net/TuVN2/1/
Looking at your markup, I guess you want to run requestCustomerInfo() and not submit. If you submit the response will never be handled. To do this you would move the function call into the keyup handler:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
requestCustomerInfo();
}
});
I would also not recommend hand rolling your ajax handler. Consider using a library like jQuery.

How to check input validation using Ajax connect to database (jsp)

The code is to check if the university input from user already exists in database. If yes, then submit the input and go to the next page; if not, then send user an alert message and stay on the same page, which is choose_university.jsp. The checkUniversity.jsp is used to connect to the database and do the checking.
But the code is not doing it. I have spent hours on it and still can't figure it out. Could anyone please tell me what's wrong with it and show me how to fix it? It's due tomorrow. Please help me.
choose_university.jsp is following:
<%#page import="java.util.*"%>
<html>
<head><title>Provide degrees - choose university</title>
<script type="text/javascript">
function validate() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var u = document.getElementById("university").value;
var url = "checkUniversity.jsp";
url = url + "?university=" + u;
xmlHttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
document.getElementById("university").innerHTML = xmlhttp.responseText;
}
}
alert("yea we got 55555");
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHtp;
}
</script>
</head>
<body>
<br> If you can't find your university, please provide it in the following and hit submit <br>
<form method="post" action="Provide_degrees_Choose_discipline.jsp" onsubmit = "return validate()">
<p>To manually add your university </p> <br>
<p> name of university: <input type = "text" id="university" name = "university" /> </p><br>
<input type="submit" name = "submit" value="submit" />
</form>
</body>
</html>
/* checkUniversity.jsp */
<% response.setContentType("text/xml") ; %>
<%# page import="javax.sql.*"%>
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%# page import="model.ApplicationModel" %>
<html>
<head><title>check university</title>
</head>
<body>
<%
System.out.println("heyheyhey");
String u = request.getParameter("university") ;
Class.forName("org.postgresql.Driver");
// Open a connection to the database using DriverManager
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/access?" +
"user=postgres&password=neshorange");
// Create the statement
Statement statement = conn.createStatement();
// Use the created statement to SELECT
// the student attributes FROM the Student table.
rs = statement.executeQuery("SELECT count(*) as c FROM universities WHERE university=\'"+ u +"\';");
if (rs.next()){
if ( rs.getInt("c") > 0) {
response.write("false");
} else {
response.write("true");
}
}
response.write("true");
%>
</body>
</html>
Try getting rid of the "return" in your onSubmit and try again. Also install firebug or another inspector (if you haven't already) so you can see javascript and request errors.
Also these days there is no need to go through all the ajax stuff like this. Look at javascript libraries like jQuery or Mootools. They can turn you js code into only a few lines.
Try this
function validate()
{
var u = document.getElementById("university").value;
$.post('checkUniversity.jsp?university=' + u, function(data) {
if(data==true) return true;
else
{
alert("user doesnot exists ")
return false;
}
});
}
You have return true if users exists from checkUniversity.jsp

xmlHttpRequest issues in a Google-like autosuggestion script

I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>

Need help for ajax

HTML Code :
<html>
<head>
<script type="text/javascript">
function checkforValid(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get.jsp?q=" + str ,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="">
Name: <input type="text" id="user" name = "user" onkeyup="checkforValid(this.value)" />
</form>
<br>
<p>Here : <span id="txtHint"></span> </p>
</body>
</html>
JSP:
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.math.*" %>
<%# page import="java.security.*" %>
<html>
<body>
<%
String user = request.getParameter("user");
out.println("Username is::"+user+".");
Connection con = null;
try
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "p2p";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "123";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery( "select * from newuser where username =" + user );
if(rs.next())
out.println("ok");
else out.println("absent");
st.close();
}
catch( Exception e )
{
out.print( "Database Error"+ e );
}
finally
{
try
{
con.close();
}
catch(Exception e1)
{
}
}
%>
</body>
</html>
When i run it on glassfish the,jsp page request.getParameter function is receiving null i.e. it is outputting User:null, so pls help and also suggest some nice projects for ajax
You are sending the username parameter to the JSP in the variable named q in your code and retrieving using the variable user
xmlhttp.open("GET","get.jsp?q=" + str ,true);
Now there can be two fixes :
First and the best
Fix in the javascript , change the name of variable from q to user like this, and let the JSP code remain unchanged.
xmlhttp.open("GET","get.jsp?user=" + str ,true);
Second Fix (not recommended)
Fix the code in the JSP.
Instead of String user = request.getParameter("user"); change it to String user = request.getParameter("q"); and let the script remain as it is...
I think this should do the trick.
Two alternatives for you.
1: Chage request.getParameter("user"); to request.getParameter("q");
2: Submit the form using ajax and you will get the user parameter.
You are sending:
xmlhttp.open("GET","get.jsp?q=" + str ,true);
But then asking:
String user = request.getParameter("user");
It's null because you never send a "user" parameter. Change it to:
xmlhttp.open("GET","get.jsp?user=" + str ,true);
Update
A few AJAX tutorials/documentation sites:
http://www.xul.fr/en-xml-ajax.html
http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html
http://www.hunlock.com/blogs/AJAX_for_n00bs (and many other docs in there)
http://www.ibm.com/developerworks/web/library/wa-ajaxintro1/index.html
And, of course, BalusC's blog:
http://balusc.blogspot.com/2009/05/javajspjsf-and-javascript.html

Categories

Resources