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);
Related
I' m working on an assignment that requires me to get data from the URL http://quotes.rest/qod?category=inspire ; specifically, the contents of the <quote> and <author> tags.
To do this I use a XMLHttpRequest; problem is, if I set xhr.responseType = 'document' (or if I use xhr.responseXML ), the variable I try to put the request in becomes null.
If I use xhr.responseText, I get the correct representation of the site in string form, and I could solve the problem working with that, but that's not how I'm intended to do it. I tried to parse the string into a XML document, but in the string I get from xhr.responseText every <> bracket is replaced with a ", causing the parsing to produce an incorrect XML document.
Please help me solve one of these two problems, either getting the XML document or the string in the correct XML syntax, thank you very much.
var doc;
var x;
function submit() {
var xhr = new XMLHttpRequest();
// here adding xhr.responseType = 'document' doesn' t change the outcome
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
doc = xhr.responseXML;
}
}
xhr.open('get', 'http://quotes.rest/qod?category=inspire', true);
xhr.send();
}
function trial(){
x = doc.getElementsByTagName("quote")[0].childNodes[0].nodeValue;
//by this point doc is null, so I get an error here
console.log( x );
}
<h5>Press to see the quote of the day:</h5>
<input type="submit" value="Start" onclick="submit()">
<!-- the first button fetches the data from the URL -->
<input type="submit" value="Trial" onclick="trial()">
<!-- the second one is supposed to show on console the quote -->
It's interesting that if you send Accept request header like this
xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml")
then it responses as XML.
var doc;
var x;
function submit() {
var xhr = new XMLHttpRequest();
// here adding xhr.responseType = 'document' doesn' t change the outcome
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
doc = xhr.responseXML;
}
}
xhr.open('get', 'http://quotes.rest/qod?category=inspire', true);
xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml");
xhr.send();
}
function trial(){
x = doc.getElementsByTagName("quote")[0].childNodes[0].nodeValue;
//by this point doc is null, so I get an error here
console.log( x );
}
<h5>Press to see the quote of the day:</h5>
<input type="submit" value="Start" onclick="submit()">
<!-- the first button fetches the data from the URL -->
<input type="submit" value="Trial" onclick="trial()">
<!-- the second one is supposed to show on console the quote -->
So I got this code for pulling rss feeds from another website (i asked them, and they gave me permission) I Don't know what should i Write in TAG1 and TAG2. Basically that is just my problem:
Here is the html (its an ajaxed page)
<!doctype html>
<html lang="hu">
<head>
<title>Videók</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="../js/videok.js"></script>
</head>
<body>
<h2>Van egy jó videód? Töltsd fel és kikerülhet az oldalra!</h2>
<div id="videok"></div>
</body>
</html>
And here is the Javascript for pulling
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "choose url";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
You won't be able to use javascript to pull from another web page because javascript is sandboxed when in browsers. Sandboxing means that you will only be able to send requests to the same domain that the javascript originally came from (also known as the 'same orgin policy').
You can use a serverside language like php to do the pulling and then hand it down to the javascript through ajax.
The code that you posted looks like it just makes a simple ajax call but it shouldn't work when trying to request an RSS from anything other than your own site.
It's better that you have the server side of your application fetch data for the xml and format the data how you want it.
You would have the Ajax request hit your server's end point, then your server will fetch the xml data, format it properly and respond to the request with the correct formatted data.
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
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
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.