Need help for ajax - javascript

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

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

Give a javascript alert after submit JSP without refreshing the page

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;

my ajax call doesn' send utf - 8 parameter to my server

I've got a web service in java with method FindEl(string myel) that accepts utf - 8 string paraeter
the select query should find all the elements that start with this string
Here is the code in Java - for my web service
public class locselall
{
public String FindEl(String myel ) throws ClassNotFoundException
{
//
String selectQuery = "select biz_subject from pl_biz WHERE biz_subject ILIKE '"+ myel + "%'";
//get rows
}
And there is no problem when i type in the browser to test my web service and it i selects:
http://localhost:9091/locselall/services/locselall/FindEl?myel=СИТ
it works;
and here is the html page that sends request to the server
html>
<head>
<script>
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function triming()
{
var strInput= document.getElementById('txtInput').value;
// for example I enter "ШИФ " - utf 8 cahracters
var newstr = strInput.replace(/[^\u0400-\u04FF0-9]/gi, '');
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
//var xmlObj = xmlhttp.responseXML;
//var textXML = xmlObj.documentElement.firstChild.firstChild.nodeValue;
}
}
var url = "http://localhost:9091/locselall/services/locselall/FindEl?myel="+ newstr;
document.getElementById('pr').innerHTML = url;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type= "text" id="txtInput" />
<input type="button" id="btnSearch" onClick = "triming();"/>
<div id="pr"></div>
</body>
</html>
As you see i have an alert for the url and it's exactly the same as the url which i typed in the browser to test my web service - but the response from the server is with no records selected 3
I think the problem is that my variable newstr holds utf - 8 (cyrilic )chaarcters and it's not properly send to the server and as a result it cannot select any records!
What I've tried
Added meta tag with charset = utf -8
nothing
I read that he problem might be in my tomcat server and i added
URIEncoding = "utf-8" in the server.xml file
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
Still nothing
Thanks in advance
Try using encodeURIComponent on the URL that is sent. I seem to remember seeing this issue before, where it worked with latin alphabet characters, but Cyrillic failed.
var url = "http://localhost:9091/locselall/services/locselall/FindEl?myel=" + encodeURIComponent(newstr);

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

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.

Categories

Resources