I am using Ajax to do a live search and all i want is the data t be displayed in a div called "results". However when im ding the search, it displays the search form again and then the results div. How do I go by solving this?
Here is the ajax code:
function finding(str)
{
if (str.length==0)
{
document.getElementById("results").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("results").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","toy_search.jsp?query="+str,true);
xmlhttp.send();
}
I have added the search page here:
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*, toyShop.*,java.util.*"%>
<!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=UTF-8">
<title>Toy Search</title>
<script type="text/javascript" src="js/search.js"></script>
</head>
<body>
<h2>Toy Search</h2>
Find toy: <input type="text" name="query" id="query" onkeyup="finding(this.value)" /><br>
<%
ToyManager toyM = new ToyManagerImp();
ArrayList<ToyData> toy_data = new ArrayList<ToyData>();
String toyName = null;
String toyBrand = null;
String desc = null;
if(!MySQLConn.getInstance().isConnected()){
MySQLConn.getInstance().connect();
}
if(request.getParameter("query") != null && !request.getParameter("query").equals("")){
String query = request.getParameter("query");
toy_data = toyM.searchToy(MySQLConn.getInstance(), query);
}
%>
<div id="results">
<%
if(toy_data != null && !toy_data.isEmpty()){
for(int i = 0; i < toy_data.size(); i++){%>
<%=toy_data.get(i).getToyName()%>
<%= "<br>"%>
<% }
}
%>
</div>
</body>
</html>
Without seeing the rest of your code, it's hard to tell. If you want to remove the search field from the page and just display the results, I suggest somewhere in the following function you add a line of javascript that updates the css style on your search div to display: hidden.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
}
You are asking for a complete web page with your Ajax call, and you're getting one back. It's working as designed, as they say. The problem is not with your Ajax, but with what you are returning from the server. You should be returning search results data, not a web page that happens to have search results data on it. Make the display of the static HTML elements on the page conditional on the method used to get the page. For instance, if the Ajax call looked like this:
xmlhttp.open("GET","toy_search.jsp?query="+str+"&format=fragment",true);
you would hide the HTML because of the &format=fragment part of the URL, leaving you with only the HTML that should be injected into the results div. In normal (non-Ajax) use, where the page is either being opened initially or there is a direct link to search results, the &format=fragment portion of the URL would not be present, and the user would load the entire page.
Related
I am trying to retrieve data stored in XML file using JavaScript. But after clicking on button there is no response. Nothing happens after clicking on button. It is even not showing any error and no output. I am unable to understand what is wrong with following code. Please help.
<html>
<head>
<title>Requesting XML data in AJAX Student information</title>
<script language="JavaScript">
function getData()
{
var xhr;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xhr=new XMLHttpRequest();
//xhr.overrideMimeType("text/xml");
}
else
{
// code for IE6, IE5
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
var n=xhr.responseXML;
dispData(n);
}
}
xhr.open("GET","student.xml",true);
xhr.send();
}
function dispData(xmlDoc)
{
var a,f1,f2,f3,f4,disp;
//using javascript properties
a=xmlDoc.documentElement;
f1=a.firstChild;
f2=f1.nextSibling;
f3=f2.nextSibling;
f4=f3.nextSibling;
disp="<b>using javascript properties</b><br>";
disp=disp+"PRN:"+f1.firstChild.nodeValue+"<br><br>Name of Student:"+f2.firstChild.nodeValue +"<br><br>Lives in :"+f3.firstChild.nodeValue+"<br><br>Contact Details:"+f4.firstChild.nodeValue;
//accessing XML elements by name
var t=xmlDoc.getElementsByTagName("stname");
var f=xmlDoc.getElementsByTagName("mobile");
disp=disp +"<br><br><b>Accessing XML elements by name</b><br>Student Name: " +t[0].firstChild.nodeValue+ " <br><br>Call: "+f[0].firstChild.nodeValue;
document.getElementById('div1').innerHTML=disp;
}
</script>
</head>
<body>
<h1 style="background-color:black;color:white">Handling XML in AJAX Application</h1>
<button onClick="getData()">Get the Student Information</button>
<br><br><br>
<div id="div1">
text goes here...........................
</div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
xml file
student.xml
<?xml version="1.0" encoding="UTF-8"?>
<student1>
<prn>121</prn>
<stname>Vijay Sharma</stname>
<city>Chiplun</city>
<mobile>94232942090</mobile>
</student1>
I changed my XML file.It is working properly with following line of code
var t=xmlDoc.getElementsByTagName("stname");
var f=xmlDoc.getElementsByTagName("mobile");
disp=disp +"<br><br><b>Accessing XML elements by name</b><br>Student Name: " +t[0].firstChild.nodeValue+ " <br><br>Call: "+f[0].firstChild.nodeValue;
But I found error with following line of code
a=xmlDoc.documentElement;
f1=a.firstChild;
f2=f1.nextSibling;
f3=f2.nextSibling;
f4=f3.nextSibling;
disp="<b>using javascript properties</b><br>";
disp=disp+"PRN:"+f1.firstChild.nodeValue+"<br><br>Name of Student:"+f2.firstChild.nodeValue +"<br><br>Lives in :"+f3.firstChild.nodeValue+"<br><br>Contact Details:"+f4.firstChild.nodeValue;
It generate error as
Uncaught TypeError: Cannot read property 'nodeValue' of null
for following line of code
disp=disp+"PRN:"+f1.firstChild.nodeValue+"<br><br>Name of Student:"+f2.firstChild.nodeValue +"<br><br>Lives in :"+f3.firstChild.nodeValue+"<br><br>Contact Details:"+f4.firstChild.nodeValue;
So script does not work for nodeValue property.
Is nodeValue property is deprecated? If so ,then what I can used instead of nodeValue.
Please help.
in database
when i fetch the data from database onchange of drop down, actually this is the real time scenario, am using jsp you can integrate with any type of frame works ( in .java files ), concept is same.
if i run this code it show the first row information
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
var keys=document.dummy.sele.value
var urls="db_fetch.jsp?ok="+keys
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)
{
var some=xmlhttp.responseXML.documentElement;
document.getElementById("a").innerHTML=some.getElementsByTagName("empno")[0].childNodes[0].nodeValue;
document.getElementById("b").innerHTML=some.getElementsByTagName("empname")[0].childNodes[0].nodeValue;
document.getElementById("c").innerHTML=some.getElementsByTagName("empaddr")[0].childNodes[0].nodeValue;
}
}
xmlhttp.open("GET",urls,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="dummy">
<select name="sele" onchange="loadXMLDoc()">
<option>value</option>
<option value="100">100</option>
<option value="101">101</option>
</select>
</form>
id: <span id="a"></span><br>
name: <span id="b"></span><br>
address: <span id="c"></span>
</body>
</html>
db_fetch.jsp
<%# page import="java.io.*,java.sql.*" %>
<%# page contentType="text/html" pageEncoding="UTF-8"%>
<%
response.setContentType("text/xml");
String sn=request.getParameter("ok");
int i=Integer.parseInt(sn);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("jdbc:oracle:thin:#www.java4s.com:1521:XE","system","admin");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select * from emp where empno="+i);
if(rs.next())
{
out.println("<emp>");
out.println("<empno>"+rs.getInt(1)+"</empno>");
out.println("<empname>"+rs.getString(2)+"</empname>");
out.println("<empaddr>"+rs.getString(3)+"</empaddr>");
out.println("</emp>");
}
rs.close();
st.close();
con.close();
%>
above code result is
i need a result as
id 100,
name java4s
address usa
id 100,
name php4s
address usa
id 100,
name visa4s
address usa
id 100,
name usa4s
address usa
i think code may change in here
{
var some=xmlhttp.responseXML.documentElement;
document.getElementById("a").innerHTML=some.getElementsByTagName("empno")[0].childNodes[0].nodeValue;
document.getElementById("b").innerHTML=some.getElementsByTagName("empname")[0].childNodes[0].nodeValue;
document.getElementById("c").innerHTML=some.getElementsByTagName("empaddr")[0].childNodes[0].nodeValue;
}
in database address column is there
You need to use a while loop to print all ResultSet Data.
your empno is not a unique column type, so basically you need other way to identify the second row. such as count,empname and etc...
int count=0;
while(rs.next()){
count++;
if(count!=2)return;//display only the second row
//if(!"php4s".equals(rs.getString(2)))return;//display only the php4s row
out.println("<emp>");
out.println("<empno>"+rs.getInt(1)+"</empno>");
out.println("<empname>"+rs.getString(2)+"</empname>");
out.println("<empaddr>"+rs.getString(3)+"</empaddr>");
out.println("</emp>");
}
I am tryint to create a little RadioPlayer that works online . Now this is the JavaScript Code that i have
function changeLink(link)
{
/* this changes the link and plays the radio*/
var radio= document.getElementById("radio");
radio.src = link;
radio.play();
}
function jsonLoad()
{
var xmlhttp = new XMLHttpRequest();
var url = "playList.txt";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
readJSON(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function readJSON(obj)
{
var list = "<ui>";
for (var i = 0; i < obj.length ; i++)
{
list += "<li><a href='javascript:changeLink(" +"\"" + obj[i].radioLink + "\"" +");'>" + obj[i].name + "</a></li>";
}
list += "</ui>";
document.getElementById("radioLoad").innerHTML = list;
}
Also this is the HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> My Radio Player</title>
<script src="Script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="jsonLoad()">
<p>This is the link that i will change his property</p>
<audio id="radio" src="#" controls autoplay preload="auto" ></audio>
</audio>
<br>
<p id="radioLoad">
</p>
</body>
Things is that locally the JSON File is perfectly working, and the webpage shows as i expected. When i put it on a server though, it's like the JSON file is not loaded and the other fuction (readJSON(myArr);) is not fired. Seems that there is something wrong with the IF Condition but i don't know excatly why. Can somebody help me?
EDIT: Seems that the code only works locally in Google Chrome. In internet explorer the links are generated but they don't play the radio when i click on them. Also on the iphone simulator that i tested, the audio tag is not working properly. I will try on different webbrowsers also.
EDIT2: it works now. I managed to figure outthe issue. It was nothing wrong with the code, it was with the server i was hosting on. So i changed the web hoster and now it works. You can see it here:
http://radioplay4all.16mb.com/
Thank you anyway :)
Without debugging it myself I can't be sure, but I'm pretty sure that your problem is in your readJSON() function, when you try to get the .length property of an object (JSON.parse() returns a javascript object), since objects don't have a .length property. To find the number of keys an object has, you could use Object.keys(myArr).length. So in your for loop, obj.length is Null, so i can't be less than Null, so it doesn't execute. So if you replace i < obj.length with i < Object.keys(obj).length that should fix the problem.
I'm building a project that uses a function called Chat.fetch(); it's an asynchronous function that pulls an array of strings from the server. It's an ajax function that for purposes of the project is already defined, I just have to call it correctly. There is another function we are given called Chat.display() which takes a string and displays it in bulleted form on the console. Right now this is what I've got:
I'm getting an error that says cannot read property length of undefined. So I guess.length is undefined for superArray? The goal is to create this function and use it as the call back function for Chat.fetch(). Do you guys have any idea why I'm getting this .length error? I'm pretty confused. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://chatbuilder.hackreactor.com/ChatBuilder.js"></script>
</head>
<body>
<script>
Chat.guide.start();
<h2>Borken Chat</h2>
<input class="draft" type="text"/> <button class="send" disabled>send</button>
<ul class="messages">
<script>
var list;
var superArray=[];
darray=function(superArray){
var y=superArray.length;
for(i=0;i<y;i++){
Chat.display(x[i]);
}
}
Chat.fetch(darray(list));
</script>
</ul>
</body>
Here's a simple page that uses Ajax
<!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","<<URL>>",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Results will go here</h2></div>
<button type="button" onclick="loadXMLDoc()">Get Results</button>
</body>
</html>
See where the xmlHttp.responseText is used? That's where you'll get your strings.
I don't have any clue what code you have, but the basic idea is something like this (using jQuery, don't know if that is in your stack or not). And this assumes Chat.fetch() is synchronous, otherwise you'll need to trigger an event when it's done or use a promise or something.
messages = Chat.fetch();
for (i=0; i<messages.length; i++) {
$('#chat-window').append( '<br>' + messages[i] );
}
I've got a drop down in the HTML that needs to be populated dynamically with a list of userIds from the database. Hence, I need to execute the JavaScript function calling the Java function to query the DB before the HTML page loads. As I need to execute the JS function before the page loads, I'm importing the Javascript (Users.js) in the head section and calling my JS function (findActiveOrganisationsRequest('findActiveOrganisations') on the atload() method in the Body tag of the HTML.
Q1. Whats the best way to get that JS function to run before form loads so I can populate the dropdown? Will the above do the trick? My HTML is:
<!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>Sample User Registration</title>
<script language="javascript" src="js/Users.js"> </script>
</head>
<body atload="findActiveUsersRequest(findActiveUsers)">
<H2>User Registration</H2>
<div id="userAccessForm" >
<form name="userAccessForm" id="userAccessForm">
<div id="userAccessResults" style=" width : 364px; float:left;"></div><br> <table width="100%" border="1px">
<tr><td> <p>Organisation *<br>
<select name="UserID" id="UserID"> <option value="Choose your Organisation" selected>Choose Username</option>
<option value="1">Dynamically populate User1</option> <option value="2">Dynamically populate User2</option> <option value="3">Dynamically populate user3</option> </select> </p><td>
<input name="submit" type="submit" id="submit" value="Submit"> <input name="reset" type="reset" id="cancel" value="Cancel">
</td></tr>
<tr><td>
<div id="UserResults" style=" width:353px; float:left;"></div></td></tr>
</table>
</form></body>
Q2. Now, how do I populate the DropDown with the list returned back by the JS function. My Javascript function is as follows:
function findActiveUsersRequest(findActiveUsers){
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() {
var returnText = xmlhttp.responseText;
document.getElementById("UserResults").innerHTML=returnText;
};
var loadingHtml = "<img border=\"0\" src=\"images/busy.gif\" width=\"50\" /> Active Users Details...";
document.getElementById("UserResults").innerHTML=loadingHtml;
xmlhttp.open("GET","mets?action=users&userAction="+findActiveUsers);
xmlhttp.send();
}
As evident, the last 2 lines of the above JS function send a HTTP request which gets caught by the servlet, which then:
checks for the parameters coming in the HTTP request,
Gets the results from the Database
Creates a StringBuffer array in response in the format as "UserID - UserName". But I'm not sure that this is the best way of doing it.. Any help/suggestions will be most appreciated!
Sends that response as follows: sendResponse(response.getWriter(), stringBuffer)
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class RequestActionFactory {
#SuppressWarnings("unchecked")
public static Action getAction(HttpServletRequest request) {
// Retrieve action parameters
String action = request.getParameter("action");
String userAction = request.getParameter("UserAction");
// Validate
if (action != null) {
// Event request
if (action.equals("users")) {
List<UserIdDTO> userDTOList = getActiveUsers(); //Gets the UserIds from the DB
StringBuffer[] stringBuffer = new StringBuffer[userDTOList.size()];
for (UserIdDTO userDTO : userDTOList) {
for(int i=0; i<userDTOList.size(); i++) {
stringBuffer[i] = new StringBuffer();
stringBuffer[i].append(responseValue(userDTO));
}
}
sendResponse(response.getWriter(), stringBuffer);
}
}
return null;
}
private StringBuffer responseValue(UserIdDTO userDTO){
StringBuffer strBuffer = new StringBuffer();
strBuffer.append(userDTO.getId());
strBuffer.append(" - ");
strBuffer.append(userDTO.getuserName());
return strBuffer;
}
public static void sendResponse(PrintWriter writer, StringBuffer[] stringBuffer) {
if (stringBuffer != null) {
for(int i=0; i<stringBuffer.length; i++) {
if(null!=stringBuffer[i]) {
writer.write(stringBuffer[i].toString());
}
}
} else {
// TODO write to log
}
}
}
Once the Java Servlet sends a response back, it gets caught in the JS functions mentioned above as:
xmlhttp.onreadystatechange = function() {
var returnText = xmlhttp.responseText;
document.getElementById("UserResults").innerHTML=returnText;
};
So, I am successfully able to display the array in the UserResults DIV tag on my form as:
1 - john.Smith
2 - Adam.smith
3 - Peter.smith
But how can I use this array to populate my drop down in the form?
Any help will be most appreciated!
To call you js function use jQuery:
jQuery(document).ready( function() {
// You init code here
});
Use json to serialize your collection from java and deserialize it on javascript side.
On java side to serialize to json:
Collection<YourType> myCollection = ... ;
Gson gson = new Gson();
String json = gson.toJson(myCollection);
// Write json to response
On js side:
var myCollection = JSON.parse(responseText);
for(i = 0l i < myCollection.length; i++) {
var element = myCollection[i];
}