xmlHttp.responseText Unknown Error define - javascript

I have create a javascript in an html (using xmlHttp.responseText) page where I am requesting a value from an aspx page that queries for a usernumber of a username in the database (MSSQL). when i load the html (IE8), i got this "Unknown Runtime Error Line: 30". What supposed to be causing the problem? need help. Here is my code:
Here is the HTML page and the Javascript:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showUsernum(str)
{
var xmlHttp;
if (str=="")
{
document.getElementById("textExists").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)
{
//alert(str);
document.getElementById("textExists").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("GET","http://localhost/Base_Data/default.aspx?q="+str,true);
xmlHttp.send();
}
</script>
</head>
<body>
<form action="" method="post">
<label>UserName
<input type="text" name="textUser" id="textUser" onchange="showUsernum(this.value)">
</label>
</form>
<br/>
<div >
<form name="form1" method="post" action="">
<label>
<div id="textExists">Exists?</div>
</label>
</form>
</div>
</body>
Here is my ASP code.
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
SqlConnection conn;
string connection = ConfigurationManager.ConnectionStrings ["BaseData"].ConnectionString;
conn = new SqlConnection(connection);
string sql = "SELECT USERNUM FROM useraccount WHERE USERNAME ='" + Request.QueryString["q"] + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
string contNm = Convert.ToString(cmd.ExecuteScalar());
Response.Write("textExists=" + contNm );
conn.Close();
}
Really appreaciate any response. Thank you.

The problem is that you're trying to assign whole page, including <html> tag and everything, into a single DOM element and IE doesn't really like that.
To have the server send only raw HTML without whole document you need to clear the Response. In addition you are not disposing properly of the database objects and you are exposed to SQL Injection attacks, so optimized code would be:
string connection = ConfigurationManager.ConnectionStrings ["BaseData"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
conn.Open();
string sql = "SELECT USERNUM FROM useraccount WHERE USERNAME=#user";
string contNm = "";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#user", Request.QueryString["q"]);
contNm = Convert.ToString(cmd.ExecuteScalar());
}
Response.Clear();
Response.Write("textExists=" + contNm);
Response.End();
conn.Close();
}

Related

Displaying Order History without using tables

i am new to UI devlopment.I use to do coding but i have been asked to get the value from xml and display order history without using tables.I am getting xml from jax-rs and want to display on html.
My Xml is:
<orderHistory>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039011
</detail_url>
<lineItemCount>ssolineItemCount</lineItemCount>
<order_id>7039012</order_id>
<sort_date>1448316</sort_date>
<status>Shipped</status>
<store_label>SSO Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>11.76</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039009
</detail_url>
<lineItemCount>tsolineItemCount</lineItemCount>
<order_id>7039009</order_id>
<sort_date>1448316</sort_date>
<status>Cancelled</status>
<store_label>Teacher Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>15.25</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orderHistory>
My Html is like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript">
var xmlhttp;
function init() {
// put more code here in case you are concerned about browsers that do not provide XMLHttpRequest object directly
//xmlhttp = new XMLHttpRequest();
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function getdetails() {
var empno = document.getElementById("empno");
var url = "http://localhost:8080/NewShot/schl-api/myresource/com/";
xmlhttp.open('GET', url, false);
xmlhttp.send();
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
//alert('Inside');
var xmlData = xmlhttp.responseXML;
if (!xmlData) {
xmlData = (new DOMParser())
.parseFromString(
xmlhttp.responseText,
'text/xml');
}
// alert('Content'+xmlData);
var store , O_url ,status,total,description,tracknum,litncount,trackhrf,subdate,sdate,durl,elements;
var conference = xmlData
.getElementsByTagName("orders");
for (var i = 0; i< conference.length; i++) {
// alert('In For');
store = conference[i].getElementsByTagName("store_label")[0].firstChild.data;
O_url = conference[i].getElementsByTagName("order_id")[0].firstChild.data;
status = conference[i].getElementsByTagName("status")[0].firstChild.data;
total = conference[i].getElementsByTagName("total")[0].firstChild.data;
description = conference[i].getElementsByTagName("description")[0].firstChild.data;
tracknum = conference[i].getElementsByTagName("tracking_num")[0].firstChild.data;
litncount = conference[i].getElementsByTagName("lineItemCount")[0].firstChild.data;
trackhrf = conference[i].getElementsByTagName("tracking_href")[0].firstChild.data;
subdate = conference[i].getElementsByTagName("submitted_date")[0].firstChild.data;
sdate = conference[i].getElementsByTagName("sort_date")[0].firstChild.data;
durl = conference[i].getElementsByTagName("detail_url")[0].firstChild.data;
//alert(date+" "+name+" "+url);
elements +="StoreType::"+store+ "<br>" +"OrderUr::"+ O_url + "<br>" +
"Status::"+status+"<br>"+"Total Bill::"+total+"<br>"+""+"Item Description::"+description+"<br>"+"Trackinh Number::"+tracknum+"<br>"+
"LineItemCount::"+litncount+"<br>"+"Tracking Link::"+trackhrf+"<br>"+"Submission Date::"+subdate+"<br>"+"Sort Date::"+sdate+"<br>"+"DetailUrl::"+durl+"<br><br>";
}
document.getElementById("demo").innerHTML= elements;
/* date = conference[0]
.getElementsByTagName("date")[0].firstChild.data;
name = conference[0]
.getElementsByTagName("name")[0].firstChild.data;
url = conference[0]
.getElementsByTagName("url")[0].firstChild.data;
*/
// alert('Name'+name+'Date'+date+'url'+url);
} else {
name = "";
date = "";
url = ""
alert("Invalid Employee ID");
}
} else {
alert("Error ->" + xmlhttp.responseText);
}
}
</script>
</head>
<body onload="init()">
<h1>Call Scholastic Service </h1>
<table>
<tr>
<input type="button" value="Get Details" onclick="getdetails()"/>
</tr>
</table>
<p id="demo"></p>
</body>
</html>
I want to display value without using table in following format:
Store Label: <Value> LineItem Count:<Value>
OrderId: <Value> LineItem Count:<Value>
Status Times: <Value> Tracking Link:<Value>
Total: <Value> Submission Date:<Value>
Description: <Value> Date Sorting:<Value>
Tracking Number:<Value>
Detail Url:<Value>
I tried using but it was not proper.
Thanks

want to change a .jsp file into .java

i am doing an autocomplete. it works nicely. but i wanted the second jsp file as .java file. i tried my best. i cant change it.please help me. the main problem is request.getparameter();
JSP Ajax Autocomplete box
autocomplete.jsp:
<%#page import="java.sql.*"%>
<html>
<head>
<script type="text/javascript">
function showData(value){ ``
xmlHttp=GetXmlHttpObject()
var url="auto.jsp";
url=url+"?name="+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;
}
}
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;
}
</script>
</head>
<body>
<form name="employee">
<input type="text" name="name" id="name" onkeyup="showData(this.value);"><br>
<div id="mydiv"></div>
</table>
</body>
</html>
auto.jsp (second jsp file)
<%# page import="java.sql.*" %>
<%
String name = request.getParameter("name").toString();
String buffer="<div>";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from data where name like '"+name+"%'");
while(rs.next())
{
buffer=buffer+rs.getString("name")+"<br>";
}
buffer=buffer+"</div>";
response.getWriter().println(buffer);
}
catch (Exception e) {
System.out.println(e);
}
%>
I think you want a java file for search response while typing.
You can do this by creating a Servelet file.
Create a servelt for /auto?name=value and map using web.xml.

javascript code is not working in browser?

Here is my code it will send get request and renders some content of the response in html.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>
<script type="text/javascript">
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.send();
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
</script>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
<div id="placeholder"></div>
</body>
</html>
this code is working perfectly when i run in eclipse browser. but its failing in Browser.
I have checked browser configuration for script enabling and its enabled. and also no issue with browser configuration.
Im new to javascript http requests.
Please suggest
I read somewhere that the Eclipse browser doesn't adhere to the same origin policy [Wikipedia]. That's why it is possible to make an Ajax request to an external URL, something that is not possible by default in a "normal" browser.
And indeed if I try to run your code [jsFiddle], I get the following error:
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
There are multiple ways to work around the same-origin policy [SO]. In your case it seems that the service supports JSONP [SO].
With JSONP, your not making an Ajax call to the server, but instead you are using the URL with a dynamically created script element. Script elements are not restricted by the same-origin policy and therefore can load data (code) from other servers.
The server will return a JavaScript file which contains a single function call. The name of the function is specified by you via a query parameter. So, if the JSON response is usually:
{"message":"accurate","cod":"200", ...}
by adding the argument callback=foo to the URL, the server returns
foo({"message":"accurate","cod":"200", ...});
(follow this URL to see an example for your service)
This response can be evaluated as JavaScript. Note that you can not turn every JSON response into JSONP. JSONP must be supported by the server.
Here is a complete example:
// this function must be global since the script is executed in global scope
function processResponse(obj1) {
document.getElementById("placeholder").innerHTML =
obj1.message + " " + obj1.list[0].name;
}
function httpGet() {
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
// the following line is just to explictly show the `callback` parameter
url += '&callback=processResponse';
// ^^^^^^^^^^^^^^^ name of our function
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
DEMO
If you google for JSONP, you will find more information [Wikipedia] and tutorials.
I think ur xmlhttprequest instance is not getting created. It is some time browser dependent try this..
var xmlhttp;
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)
{ your code }
In addition to needing a cross browser xmlhttpquest (which for that alone I'd use jQuery), you also need to wait for the document ready before accessing the city by id... that is, move your script block after your city definition (and I think you may need a form, depending on browser).
Perhaps something like this
<body>
<form>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
</form>
<script type="text/javascript">
function httpGet() {
if (typeof (document.getElementById("city")) == 'undefined') {
alert("Maybe console.log our alarm... but the sky appears to be falling.");
}
var xmlHttp = null;
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) {
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
}
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp.open("GET", url, false);
xmlHttp.send();
}
</script>
<div id="placeholder"></div>
</body>
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.onreadystatechange = function(){
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
xmlHttp.send();
}

Modifying server side text file

Currently I am working on static HTML website. Now I am using following javascript code to read server side text file:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
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("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "results.txt", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>content</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Here on click event data is just displayed.But now I want to change the content of text file on click event.I want to increment the number by 1 which resides in the file as content.
Please help me to do this...Thank you so much in advance.!!
EDIT:
I am using windows hosting.
You may do it like this
This is the index page. I have done it in JSP.
index.jsp
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
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("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "newjsp.jsp", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">
<h2>content</h2>
</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Then the server side coding
newjsp.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.io.*"%>
<%
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/sar/Documents/NetBeansProjects/WebApplication1/web/results.txt"));
// change the path to the txt file
String line;
int a = 0;
if((line = in.readLine()) != null)
a = Integer.parseInt(line)+1;
else
a = 1;
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Users/sar/Documents/NetBeansProjects/WebApplication1/web/results.txt"));
// change the path to the txt file
pw.println(a);
pw.close();
out.println(a);
}
catch(Exception e)
{
e.printStackTrace();
}
%>
You will have to create a results.txt file at the location specified.

using ajax how to send parameter from 1 jsp page to another servlet

I am using azax to dynamically change the jsp page and I want to send data from that jsp page to a servlet. The jsp code:
<input type="submit" oninput="loadXMLDoc(this.value)" value="ok" name="ok">
<div id="myDiv">
Insert Id:<input id="p1" type="text" name="edit1" value=""style="visibility:hidden" size="30"/>
</div>
function loadXMLDoc(str){
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","edit?q="+str,true);
xmlhttp.send();
}
The servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); Connection conn=null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "studentdatabase";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "1234";
String student=request.getParameter("str");
Statement stmt;out.println(student);
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select name1,telephone,email,department from studentinfo where studentid='"+student+"";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String s = rs.getObject(1).toString();
out.println("<p> " +s+ "</p>");
}
conn.close;
//System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
The String student shows null even though there is value in the database for studentid=student.
Since you are using HTTP-POST you have to put your params into the send method.
...
var params = "q="+str;
xmlhttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
...

Categories