Solved

Ajax gets empty responseText in Solr in Firefox

Posted on 2010-11-28
13
1,463 Views
Last Modified: 2012-05-10
I'm trying to test the Solr search with the following Ajax code. It works in IE, but not in Firefox. In Firefox, xmlhttp.responseText is always empty.

I guess it might be the same origin problem, but I don't know how to work around that. Thanks.
<script type="text/javascript">

function showResult(str)

{

 

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)

    {

    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;

    }

  }

xmlhttp.open("GET","http://mydomain.com:8983/solr/select?q="+str+"&wt=json",true);

xmlhttp.send();

}

</script>







			<form name="search">

				<div> 		

					<input name="q" type="text" onKeyUp="showResult(this.value);">

			 	</div>

			 

				<div id="livesearch">

				</div>	

			</form>

Open in new window

0
Comment
Question by:rxzang
  • 8
  • 4
13 Comments
 
LVL 3

Assisted Solution

by:roynaufal
roynaufal earned 500 total points
ID: 34225018
i suggest u use jquery, makes ajax much much simpler, and compatible
all the above simply becomes:
<head>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

then you can do an ajax function like this:


function getData(str) {
  $.ajax({
	url: "http://mydomain.com:8983/solr/select?q="+str+"&wt=json",
	type: 'GET',
       dataType: 'json',
	success: function(response, textStatus, XMLHttpRequest) {
                         $("#livesearch").html(response);;
                        //if data is retreived as json, u can use response.name  to access a 'name' field, or loop through them using a js each loop, if it's not json, remove the datatype above
	},
	error: function(XMLHttpRequest, textStatus, errorThrown) {
               alert('could not get data ');
	} 
  });


}

Open in new window

0
 
LVL 16

Expert Comment

by:BurnieP
ID: 34225521
It seems to be a known bug :

http://www.nczonline.net/blog/2009/07/09/firefox-35firebug-xmlhttprequest-and-readystatechange-bug/

I am posting the WorkArounds from that link I posted.

Workarounds
Even though the readystatechange event isn’t firing, the readyState property is actually getting updated. So, it is possible to poll for changes in readyState on your own to determine when to determine that the response has been received. This is the approach taken in the YUI 2.7 Connection Manager, so if you’re using this utility, your code should continue to work without incident (the YUI 3 Beta 1 equivalent uses onreadystatechange, so users of that will be affected).

If that approach seems too hacky for you, there is another workaround. The Firefox XMLHttpRequest object supports the W3C Progress Events, all of which continue to work appropriately. The progress events are:

•load - fires when a response is received from the server.
•error - fires when a network error occurs.
•abort - fires when the request has been aborted.
•progress - fires when a partial amount of data is available from the response.
Of these four, one of the first three will always be fired once a request is deemed to have been completed (by completion, I mean the connection is no longer open). Since readystatechange continues to work in all other browsers, you may need a temporary fork in your code to make use of the progress events in the meantime, such as:

var xhr = new XMLHttpRequest();

if (firefox3_5){
    xhr.onload = xhr.onerror = xhr.onabort = function(){
        processResponse(xhr);
    };
} else {
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4){
            processResponse(xhr);
        }
    };
}

xhr.open("get", "/url", true);
xhr.send(null);Normally, I wouldn’t recommend browser-specific hacks, but in this case we’re not sure how long the issue will be out there and therefore don’t know how long our code will continue to break. At least this workaround will continue to work even after this issue has been addressed.

0
 

Author Comment

by:rxzang
ID: 34235254
Hi roynaufal, I tried your code.

For Firefox, it always prints "could not get data".
For IE, no error and no result shows up.
0
 

Author Comment

by:rxzang
ID: 34235273
I saw some other people use

dataType: 'jsonp'

I tried this also, no error shows up on both Firefox and IE. But still no result returned.
0
 
LVL 3

Assisted Solution

by:roynaufal
roynaufal earned 500 total points
ID: 34235308
do you use firebug ?
if not , download it (addon for firefox)

then restart firefox, open your page,
click the firebug icon in the bottom right corner, the window will split and you will see the firebug console, click the 'net' tab, enable it (from the arrow button),
click clear so it clears all results,
now click whatever executes the code, you will see in the firebug console the request happening, click on it, and click 'response'
paste that here (or at least part of it)
this way it will be easier to figure out the issue

if you're getting the no data alert, doublecheck and make sure the URL you are using is correct,try executing the link on its own
you can also try removing the datatype altogether to see what happens
but please send the above info so I can see what the issue is :)
0
 
LVL 3

Expert Comment

by:roynaufal
ID: 34235313
oh btw, in the net tab after you enable it, click the 'all' tab so you can see all the requests
the XHR shows only ajax requests (your request will show there as well, but "all" can show us maybe something unexpected)
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:rxzang
ID: 34244085
I followed the instructions and get the Response:   (use   dataType: 'jsonp'  )

{"responseHeader":{"status":0,"QTime":0,"params":{"q":"video ","wt":"json","callback":"jsonp1291159122771"}},"response":{"numFound":3,"start":0,"docs":[{"id":"MA147LL/A","name":"Apple 60 GB iPod with Video Playback Black","manu":"Apple Computer Inc.","includes":"earbud headphones, USB cable","weight":5.5,"price":399.0,"popularity":10,"inStock":true,"manufacturedate_dt":"2005-10-12T08:00:00Z","cat":["electronics","music"],"features":["iTunes, Podcasts, Audiobooks","Stores up to 15,000 songs, 25,000 photos, or 150 hours of video","2.5-inch, 320x240 color TFT LCD display with LED backlight","Up to 20 hours of battery life","Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video","Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication"]},{"id":"EN7800GTX/2DHTV/256M","name":"ASUS Extreme N7800GTX/2DHTV (256 MB)","manu":"ASUS Computer Inc.","weight":16.0,"price":479.95,"popularity":7,"inStock":false,"manufacturedate_dt":"2006-02-13T00:00:00Z","cat":["electronics","graphics card"],"features":["NVIDIA GeForce 7800 GTX GPU/VPU clocked at 486MHz","256MB GDDR3 Memory clocked at 1.35GHz","PCI Express x16","Dual DVI connectors, HDTV out, video input","OpenGL 2.0, DirectX 9.0"]},{"id":"100-435805","name":"ATI Radeon X1900 XTX 512 MB PCIE Video Card","manu":"ATI Technologies","weight":48.0,"price":649.99,"popularity":7,"inStock":false,"manufacturedate_dt":"2006-02-13T00:00:00Z","cat":["electronics","graphics card"],"features":["ATI RADEON X1900 GPU/VPU clocked at 650MHz","512MB GDDR3 SDRAM clocked at 1.55GHz","PCI Express x16","dual DVI, HDTV, svideo, composite out","OpenGL 2.0, DirectX 9.0"]}]}}


The data is correct. How to display it?  It does not show up in the div. It seems that it doesn't go to "success:" because there is no output even when I put alert("test"); in the success: {}.
0
 

Author Comment

by:rxzang
ID: 34245630
I'm trying to get the search result on solr. Do I need to do anything on the solr side?
0
 

Author Comment

by:rxzang
ID: 34245815
Success works when I put

jsonp: 'json.wrf',  

Now I can get the jsonp:

jsonp1291188423714({"responseHeader":{"status":0,"QTime":1,"params":{"q":"v","json.wrf":"jsonp1291188423714","wt":"json"}},"response":{"numFound":4,"start":0,"docs":[{"id":"VDBDB1A16","name":"A-DATA V-Series 1GB 184-Pin DDR SDRAM Unbuffered DDR 400 (PC 3200) System Memory - OEM","manu":"A-DATA Technology ....

How can I parse it? Thanks.
0
 

Author Comment

by:rxzang
ID: 34245873
Solved. Thanks.
0
 

Accepted Solution

by:
rxzang earned 0 total points
ID: 34245888
This is my final solution:

Thanks for all your help!

<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type='text/javascript'>

function getData(str) {
  $.ajax({
	url: "http://mydomain.com:8983/solr/select?q="+str+"&wt=json",
	type: 'GET',
        dataType: 'jsonp',
	jsonp: 'json.wrf',
	success: function(response, textStatus, XMLHttpRequest) {
                         $("#livesearch").html(response.response.docs[0].name);

                        //if data is retreived as json, u can use response.name  to access a 'name' field, or loop through them using a js each loop, if it's not json, remove the datatype above
	},
	
	error: function(XMLHttpRequest, textStatus, errorThrown) {
               alert('could not get data ');
	} 
  });


}

</script>

			<form name="search">
				<div> 		
					<input name="q" type="text" onKeyUp="getData(this.value);">
			 	</div>
			 
				<div id="livesearch">
				</div>	
			</form>

Open in new window

0
 
LVL 3

Expert Comment

by:roynaufal
ID: 34246136
ah ok,
sorry for the late reply
that's nice to hear, good luck with the project :)
if you need more help, we're all here!
0
 

Author Closing Comment

by:rxzang
ID: 34276867
good
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now