I am trying working off of https://wiki.apache.org/solr/SolJSON tutorial. I have put my url for solr in the code, copied from solr admin query result to make sure the query should return something.
I try typing in "title:Asian" into text box (that field/search term combo returned results in the admin console query) but when the button is hit, textbox just clears and nothing in output spot.
I used the dev tools from [F12] key of browser to check console and see there was no errors given there, such as for syntax, so not due to that.
Perhaps I am understanding how the url for query works or should be here? If I leave out local host part as shown I just get error for not specifying local full path.
Does anyone see anything wrong here, or have any ideas/tips of what more to do to try and solve the issue?
[ If I must do/add anything else to make good/better post here, please do explain so I can fix :) ]
<html>
<head>
<title>Solr Ajax Example</title>
<meta charset="UTF-8">
<script language="Javascript">
// derived from http://www.degraeve.com/reference/simple-ajax-example.php
function xmlhttpPost(strURL)
{
var xmlHttpReq = false;
var self = this;
if (window.XMLHttpRequest) { // Mozilla/Safari
self.xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
};
var params = getstandardargs().concat(getquerystring());
var strData = params.join('&');
self.xmlHttpReq.send(strData);
//document.getElementById("raw").innerHTML = strData;
return false;
}
function getstandardargs() {
var params = [
'wt=json'
, 'indent=on'
, 'hl=true'
];
return params;
}
function getquerystring() {
var form = document.forms['f1'];
var query = form.query.value;
qstr = 'q=' + escape(query);
return qstr;
}
// this function does all the work of parsing the solr response and updating the page.
function updatepage(str)
{
document.getElementById("raw").innerHTML = str;
var rsp = eval("("+str+")"); // use eval to parse Solr's JSON response
var html = "<br>numFound=" + rsp.response.numFound;
var first = rsp.response.docs[0];
html += "<br>product name=" + first.name;
var hl = rsp.highlighting[first.id];
if (hl.name != null) { html += "<br>name highlighted: " + hl.name[0]; }
if (hl.features != null) { html += "<br>features highligted: " + hl.features[0]; }
document.getElementById("result").innerHTML = html;
}
</script>
</head>
<body>
<form name="f1" onsubmit='xmlhttpPost("http://localhost:8983/solr/myCore/select?")'>
<p>query: <input name="query" type="text">
<input value="Go" type="submit"></p>
<div id="result"></div>
<p/><pre>Raw JSON String/output: <div id="raw"></div></pre>
</form>
</body>
</html>
Related
I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null.
If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that.
I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem).
How I can make to populate 'textParam' with the input text value when I press the button?
PS: I need to make it with pure javascript, not with some libraries :)
The JSP which have to process is:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
My form it look like that:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
The .js file it's this:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
The problem is here:
String textParam = request.getParameter("chatMessage");
I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js:
String textParam = request.getParameter("message");
<!doctype html>
<html>
<head>
<title>Twitter</title>
<meta charset="utf-8">
<script>
window.onload = function () {
// set up the click handler for the form button
var button = document.getElementById("submit");
button.onclick = getTweets;
}
// when you click "Get Tweets" we call this function
function getTweets() {
// set up a new XHR request
var xhr = new XMLHttpRequest();
// we're calling search.php and passing in a query string
var url = "search.php?query=";
var query = document.getElementById("query").value;
if (!query) {
query = "html5";
}
// we encode the query to handle any special characters properly
url += encodeURIComponent(query);
// this is the function that is called when the XHR request
// to our search.php script is handled, and a response sent back
xhr.onload = function () {
// if everything went okay, then send the response data
// to the displayTweets() function
if (xhr.status == 200) {
displayTweets(xhr.responseText);
} else {
var errorDiv = document.getElementById("error");
errorDiv.innerHTML = "Error getting tweets: " + xhr.status;
}
};
// make the request!
xhr.open("GET", url);
xhr.send(null);
}
function displayTweets(tweets) {
// tweets is a big long string, so we need to parse it
// into JSON first
tweets = JSON.parse(tweets);
var ul = document.querySelector("ul");
// clear existing tweets from list
while (ul.hasChildNodes()) {
ul.removeChild(ul.lastChild);
}
// add new tweets
for (var i = 0; i < tweets.length; i++) {
var li = document.createElement("li");
li.innerHTML = tweets[i].tweet;
ul.appendChild(li);
}
}
</script>
</head>
<body>
<form>
Query:
<input type="text" id="query">
<input type="button" id="submit" value="Get Tweets">
</form>
<div id="error"></div>
<ul></ul>
</body>
</html>
In the above code when I enter some text in the textbox and click on "Get Tweets" button it gives an error as Error getting tweets: 0. The search.php when executed independently without embedding in html and javascript gives accurate and required results.Can you please check the html and js code and suggest any changes in code??
Seems that the issue is CROSS-DOMAIN Ajax issue. When you execute the search.php independently, then there is no X-domain issue. But when you are embedding the code in some html, check if the html is part of the same domain or not. Also, if you are trying to run the html file from file:/// it will not work.
I am testing out some code with Python and Javascript trying to get an Ajax system set up. Basically I just want to input a word and have the python code send it back. Here is my html/javascript:
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari/Chrome
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
<p>word: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/ajaxtest")'></p>
<div id="result"></div>
</form>
</body>
</html>
and here is my python:
class AjaxTest(BlogHandler):
def get(self):
user = self.get_user()
self.render('ajaxtest.html', user = user)
def post(self):
user = self.get_user()
word = self.request.get('w')
logging.info(word)
return '<p>The secret word is' + word + '<p>'
#having print instead of return didn't do anything
When I do logging the word shows up correctly and when I hardcode str in:
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
It displays that correctly but right now without hardcoding it shows nothing. How am I supposed to send the response? I am using webapp2 as my Python framework and Jinja2 as the templating engine, though I don't think that has much to do with it. Do I need to send the HTTP headers?
If your problem is having difficulty returning a string from your post method, without rendering a template you can use the write method to accomplish that:
self.response.write('')
I believe you can change headers by just modifying self.response.headers
The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request
I am learning this stuff so my code might not be pretty... but would appreciate some help :)
I have not written the following code but got it from somewhere else off the web:
function text_xml()
{
realXmlUrl="http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
}
function response_xml()
{
if (self.http_request.readyState == 4)
{
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseText);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
And the error I am getting is:
Error: xml.getElementsByTagName is not a function
What am I doing wrong?
responseText is a string, not an XML. Are you looking for responseXML?
Update
If your script is loaded from a different domain than the XML document you're loading (http://jumac.com/del_me_fruits.xml), then XMLHttpRequest will act differently depedning on the browser.
On IE 8, it will pop up a warning window complaining that "The page is accessing information that is not under its control. This poses a security risk. Do you want to continue?" if you click yes, then it will work correctly (i.e., the XML will load and the alerts for the fruits will be displayed).
On Chrome 12, however, it doesn't pop anything and it will say that "XMLHttpRequest cannot load http://jumac.com/del_me_fruits.xml. Origin http://localhost:54671 is not allowed by Access-Control-Allow-Origin." Because of this error, the responseXML property of the request object will be null and you'll see the error you have.
There are other questions regarding cross-domain XMLHttpRequest where you may find how to solve your issues, such as Cross-site XMLHttpRequest and http://code.google.com/chrome/extensions/xhr.html.
<body>
<script type="text/javascript">
function text_xml() {
realXmlUrl = "http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML; // this doesn't have anything
}
function response_xml() {
if (self.http_request.readyState == 4) {
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseXML);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
</script>
<input type="button" value="Click me" onclick="text_xml();" />
<p><div id="ex"></div></p>
</body>
I usually love using a dictionary when working with any kind of transferring data across servers.
MkNxGn.pro provides a sleek way to make XML HTTP requests via MkNxGn Proquest.
Load Proquest, This can be separate from the code<script src="https://mknxgn.pro/scripts/Proquest_Proquest-v1.0.js"></script>
<script>
Proquest("POST",
URL_HERE,
DATA,<br>
HEADERS,
RType,
Ignore JSON errors,
Callback);
</script>
That way you could easily write:
<script>
Proquest("GET", "http://jumac.com/del_me_fruits.xml", Skip, {'Content-type': 'text/xml'}, 'response', false, function(resp) {
resp.overrideMimeType('text/xml'); //Looks like you want it to be XML if its not.
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(resp.responseXML);
});
</script>
ignoring jason's edit to rewrite it better.
Consider using a javascript libary like jquery.
jquery ajax is pretty much self explaining and you don't have to mess with brower compatibility. http://jquery.com/