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

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

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

Ajax: Data is not retrieved from XML file

I'm learning ajax and trying to display some data on a page:
This is my method that retrieves data from xml file:
function MakeXMLHTTPCall() {
var xmlHttpObj;
xmlHttpObj = CreateXmlHttpRequestObject();
if (xmlHttpObj) {
xmlHttpObj.open("GET", "http:// " + location.host + "/XmlHttpExample1/DataFile.xml", true);
xmlHttpObj.onreadystatechange = function () {
if (xmlHttpObj.readyState == READYSTATE_COMPLETE) {
document.getElementById("divResults").innerHTML = xmlHttpObj.responseText;
}
}
xmlHttpObj.send(null);
}
}
This is an html fragment defining div element that will hold data:
<form id="form1" runat="server" method="post">
<div>
<input type="button" onclick="MakeXMLHTTPCall();" value="Text XMLHTTP Call" />
<br />
<br />
<div id="divResults">{no results}</div>
</div>
</form>
This is my CreateXmlHttpRequestObject() method:
function CreateXmlHttpRequestObject() {
var xmlHttpObj;
if (window.XMLHttpRequest){
xmlHttpObj = new XMLHttpRequest();
}
else {
try {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
}
}
if (window.ActiveXObject) {
try{
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlHttpObj;
}
var READYSTATE_UNINITILIZED = 0;
var READYSTATE_LOADING = 1;
var READYSTATE_LOADED = 2;
var READYSTATE_INTERACTIVE = 3;
var READYSTATE_COMPLETE = 4;
This is my xml file:
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer>
<Firstname>John</Firstname>
<Lastname>Doe</Lastname>
<email>john.do#test.com</email>
</Customer>
<Customer>
<Firstname>Alan</Firstname>
<Lastname>Anonymous</Lastname>
<email>anon#ymous.com</email>
</Customer>
<Customer>
<Firstname>Marvin</Firstname>
<Lastname>Martian</Lastname>
<email>marvin#mars.com</email>
</Customer>
</Customers>
I debugged the code. XMLHttpRequest object is created. The problem is, the data is not displayed.
What am I doing wrong? Any suggestions?
It sounds like you need to do a little debugging. There's multiple things, that can go wrong in this setup. So try to work through these steps, and determine how much of your code actually works. You will find the bug in step 3 :)
Check that the function MakeXMLHTTPCall() is actually called. place an alert(1); statement in the top of the function, and click the button. If you don't get a popup with the text '1', then this function isn't even called. This is most likely due to syntax errors somewhere in your javascript.
Now that you have determined, that MakeXMLHTTPCall() gets called, when you click the button, check your if-statement. Place alert(1); as the first thing in the if-statement. If this don't bring a popup, then your xmlHttpObj isn't created properly. So check your CreateXmlHttpRequestObject() to see that it's working correctly.
Check that the url you're fetching actually exists. And you will find, that you accidentally have a space misplaced. That is "http:// " should be "http://"
I hope you didn't mind I gave you the explanation of how I found the bug. It is very frustrating not to know how to debug the code.

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

There is a long suffering, but I can not do cross- site request

What now is:
A page on localhost, which sends a request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://www.3dfind.ru/site/js.js');
document.getElementsByTagName('head')[0].appendChild(script);
</script>
</head>
<body>
<form method="get">
<div id='searchform'>
<table>
<td>
<input name='q' id='searchinput' type='text' value=''>
</td>
<td>
<select name='type' id='searchselect'>
<option value='1'>Val 1</option>
</select>
</td>
<td>
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
</td>
</table>
</form>
<div id='ResponseDiv'>
</div>
</body>
</html>
Then there js script on the server, which receives the request:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
var params = 'q=' + encodeURIComponent(q) + '&type=' + encodeURIComponent(type) + '&search=' + encodeURIComponent(s)
xmlHttp.open("GET", '/result.php?'+params, true)
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
If the file result.php search on the server, you get a url:
http://3dfind.ru/site/result.php?q=%E4%F4%E4%E4%F4%E4&type=1&search=%CF%EE%E8%F1%EA%21
Also in result.php I accept the GET- request :
$var = #$_GET['q'] ;
$s = $_GET['s'] ;
$typefile = $_GET['type'];
What am I doing wrong ?
Alright my man, I think you're a bit confused. Your HTML contains
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
And your Javascript contains
function MakeRequest()
but you say "Then there js script on the server, which receives the request:"
The Javascript should be on the client and sends the request.
Then I'm not even sure what you're trying to do and what's going wrong. Are you getting errors? Is it supposed to do something that it isn't?
Back to basics: use Firefox and install Firebug. Enable the "console". Open your page and do what you're trying to do. If you have Javascript errors, they'll show in the console. You can open every ajax request in the console as well so you can see if you're getting a server side error.
Yeah, I'm a bit confused what you're asking, here is a reference you may look into for cross-site xmlhttprequests here. There is another good reference to cross-site requests here also
From your other question ("cross-site request") I think I understand what you're trying to do. I think you're trying to get the results from "results.php" which is hosted in a different server.
What you need to do is change your MakeRequest() function. Instead of
xmlHttp.open("GET", '/result.php?'+params, true)
it should be
xmlHttp.open("GET", 'http://URL_OF_OTHER_SERVER/result.php?'+params, true);
Hope this helps.

Submitting a form more than once

I am try to have a forum submits more then once when a user clicks the submit button. Why? I am try to add more then one idem to a shopping cart, The shopping cart software I am using doesn't support adding more then one product at a time and I don't want to edit there core code. The hidden forum would have the product ids like '1,2,3' I'd then need the JavaScript to separate the values and post each one using AJAX to the cart. I am not great a JavaScript but I coded what I think should work but its just giving me a alert: 'There was a problem with the request.' twice. I can't see whats wrong with it, any and all help and suggestions are welcomed! Here the code:
JS
<script type="text/javascript">
function testResults (form) {
var product_id = form.product_id.value;
var quantity = form.quantity.value;
var brokenstring=product_id.split(",");
for ( var i in brokenstring )
{
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
var poststr = "product_id=" + encodeURI( brokenstring[i] ) +
"&quantity=" + encodeURI( quantity );
makePOSTRequest('post.php', poststr);
}
}
</script>
HTML
<form action="javascript:testResults(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="product_id" id="product_id" />
<input type="hidden" name="quantity" id="quantity" value="1" />
<br />
<input type="submit" name="button" value="Submit" />
</form>
<span name="myspan" id="myspan"></span>
post.php
<?php
print_r($_POST);
?>
If you want to add two items to the cart shouldnt you be doing two posts with the same item? I can just see one post per item there. You are not taking the quantity into account. But this is not the problem. In this case this is only a logic error.
For the javascript side I would recommend you to use jQuery to treat the ajax stuff because it will make your life WAY easier than regular javascript that might event not work with all browsers.
This is the link related to the POST method of jQuery: http://docs.jquery.com/Post
Hope it helps
It is against all the programming logics to post a form several times instead of having a more complex form. From what I can see or understand from your code you are trying to loop through your splitted (brokenstring) string. Your loop is not constructed where and how it should be. Anyway, if I were you, I would consider migraton to another free cart o the possibility to write one myself. From what I see you will be able to do so with a little bit of help from here.

Categories

Resources