Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New Coder
    Join Date
    Jan 2012
    Posts
    20
    Thanks
    2
    Thanked 1 Time in 1 Post

    responseText is empty?

    Dear friends:

    I am working through The Book of JavaScript by thau! and I got stuck near the end. In chapter 16, it is discussing making an-synchronized calls, using a server side .php (which I am running from my own machine locally).

    now the query.php works correctly when I run it from localhost, but the problem is that when I call it from my html page, the responseText is empty. This goes for both IE and FireFox. BTW, I'm running Win7 64Bit, and I am using the latest XAMPP with everything installed

    This problem was compounded by the fact that the book assumes that google suggestions is still in beta testing, however it is now standard google. It wanted me to use "www.google.com/complete/search?js=true&qu=" which no longer exists, I found out that I have to use "www.google/search?js=true&q=" (see the key is no longer "qu", it is now "q") Having figured that out you'd think I had it in the bag. However....

    Here is my query.php, as I said, it runs fine by itself when I type 'localhost/query.php?word=Spidey' into my browser:

    Code:
     <?php
    	include "Snoopy.class.php"; //snoopy.sourceforge.net
    	$snoopy = new Snoopy();
    	$requestedWord = $_REQUEST["word"];
    	$googleURL = "http://www.google.com/search?js=true&q=" . $requestedWord;
    	$snoopy->fetchtext($googleURL);
    	print $snoopy->results;
    ?>
    but when I call it from this .html, the responseText is empty, as shown by the alert statement in the request.onreadystatechange = function statechanged(); same thing if I just echo text out from the query.php

    Code:
    <html>
    	<head>
    		<title>Querying Google Search</title>
    		<script type = "text/javascript">
    			<!--
    				function getSuggestions(the_word)
    				{
    					var request = null;
      					if (window.XMLHttpRequest) 
      						{request = new XMLHttpRequest();}
      					else if (window.ActiveXObject)
      						{request = new ActiveXObject("Microsoft.XMLHTTP");}
      					var escaped_word = escape(the_word);
      					var the_URL = "http://localhost/query.php?word=" + escaped_word;
      					if (request) 
      					{
      						request.open("GET", the_URL);
        					request.onreadystatechange = function statechanged()
        					{
        						if (request.readyState == 4) 
        						{
        							alert(request.responseText); //shows that it is empty
        							displayResults(request.responseText);
            					}
          					}
    						request.send(null);
      					}
      					else
      						{alert("Sorry, you must update your browser before seeing Ajax in action.");}
      				}//getSuggestions
      				
      				function displayResults(the_response)
      				{
      					var the_results = eval(the_response);
      					var display_me = "";
      					var splitter;
      					var this_result = null;
      					for (loop = 0; loop < the_results.length; loop++)
      					{
      						this_result = the_results[loop];
      						if (this_result != null)
      						{
      							splitter = this_result.split("\t");
      							display_me += "<tr><td align='left'>" + splitter[0] + "<\/td><td align='right'>" + splitter[1] + "<\/td><\/tr>";
      						}
      					}
      					document.getElementById("theResults").style.height = (the_results.length + parseInt(the_results.length / 5) + 1) + "em";
      					document.getElementById("theResults").innerHTML = "<table width='100%' border='0' cellpadding ='0' cellspacing='0'>" + display_me +"<\/table>";
      				}//displayResults
      				
      				function sendRPCDone(ignore1, ignore2, word_array, count_array, ignore3)
      				{
      					var result_array = new Array();
      					for (var loop = 0; loop < word_array.length; loop++)
      						{result_array.push(word_array[loop] + "\t" + count_array[loop]);}
      					return result_array;
      				}
    			// -->
    		</script>
    	</head>
    	<body>
    		<input type = "text" size = "55" id = "theText" onKeyUp = "getSuggestions(this.value);" />
    		<div id = "theResults" style = "width:22em;border:1px black solid;padding-left:2px;padding-right:2px"></div>
    	</body>
    </html>
    I can't run it from The Book Of JavaScript's website (chapter 16 figure 9) because it uses the old Google suggestions while it was still in beta.

    Does anyone have any suggestions? Thank you for your time.

    notes: this should work like Google's own search box, i.e. a list should drop down with several suggestions all beginning with the text typed on the left, with the number of results for that suggestion to the right.
    Last edited by Spidey1980; 01-22-2012 at 06:17 AM. Reason: minor grammatical edits

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,641
    Thanks
    0
    Thanked 649 Times in 639 Posts
    I would suggest that you get an alternative book on JavaScript to learn from as the second edition of that book is a history book on how JavaScript worked eight plus years prior to when it was written and has nothing in it whatever that relates to current JavaScript coding.

    The actual cause of your error is that you need an extra line near the top of the PHP before it echos anything to set the content type to text

    header('Content-type: text/plain');

    Without that the processing doesn't know to load the result into responseText as it doesn't know whether the PHP has generated XML, text or something else and so doesn't load either responseText or responseXML.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    Spidey1980 (01-22-2012)

  • #3
    New Coder
    Join Date
    Jan 2012
    Posts
    20
    Thanks
    2
    Thanked 1 Time in 1 Post
    Thank you for the quick reply.

    I saw this book at my local library (2nd edition like you guessed) and just snatched it up; it is the only javascript book they had. Most of it still applies, I did manage to get to chapter 16 without issues (save that Google Chrome was choking on it, I have now switched to FireFox). I will be looking for another more up to date JavaScript book to continue my studies.

    Now then: that header you suggested causes the responseText to be "undefined".

    however,
    Code:
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: GET,POST");
    header("Access-Control-Allow-Methods: Content-Type");
    //adding your header here makes no difference
    those 3 give me a responseText. I have not tried just one header than the next, so I'm not sure which one does the magic. But I'll keep them as a copy/paste template, they might all come in handy.

    now my issue is the line:
    Code:
    var the_results = eval(the_response);
    The code stops there and goes no further. Inserting an alert(the_results); after this is not executed. (if I use only the header you gave me, alert(the_results); gives me the undefined that I mentioned).

    For some reason, I am getting the entire source of the page back from Google, when I just want the search results. Also, when using the real Google, the number of results per suggestion is no longer returned. The response was expected to be "suggestion1=numResults&suggestion2=numResults" or something like that so that I could split it out; it just does not work that way anymore. The "js=true" does not seem to make a difference either, the response is the same with and without it.

    I think I got what I could from this, I just have to move on. If I was requesting something from my own server, I think I could make the responseText usable and hopefully without needing eval(), which chapter 17 will get into. Of course, writing a script to talk to any outside/third party website would be tough, there is no easy way to allow for changes made to their site, unless standards are adhered to (like using the "login using facebook" feature on a site outside of facebook).

    Again, thank you for the fast reply.
    Last edited by Spidey1980; 01-22-2012 at 07:40 AM.

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,641
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Spidey1980 View Post
    Most of it still applies
    Most of it does NOT still apply. The correct way to write modern JavaScript is completely different from the antiquated way that the book suggests. While that code still works and was acceptable when it was the only way to do it, little of what is in the book comes even remotely close to being the best way to write JavaScript now.

    If you think in terms of tools then the book is giving you the equivalent of how to make a stone axe - which will still work but is nowhere near as good as a steel one.

    Statements in JavaScript that used to be used but which now serve no purpose and which should be replaced by more modern equivalents include:

    document.write
    alert
    eval

    The header I suggested was the only one that did make any difference when I was writing tutorials on how to retrieve information from the server but that may be due to the way the server is configured.

    Its a pity in some ways that I didn't have the time to write the replacement fot that book that the publishers actually asked me to write when they realised how outdated the new version of the book was.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #5
    New Coder
    Join Date
    Jan 2012
    Posts
    20
    Thanks
    2
    Thanked 1 Time in 1 Post
    First, Felgall, I want to thank you, I will be using your site extensively for a while. And from now on I will always separate my javascript out into a .js file. It makes a lot of sense, why go through so much HTML when editing to find the javascript?

    Onto my questions:

    Ex. 9
    Code:
    var name;
    name = window.location.search.substring(1);
    if ('' === name)
    document.getElementById('ex').innerHTML = 'Who are you?';
    else
    document.getElementById('ex').innerHTML = 'Hello '+name;
    So brackets are optional?
    Code:
    if(true)
    {do this;}
    else(false)
    {do this;}
    I'll probably always use them though, the above is my normal style for one liners, regardless of programming language.....

    Another question: I'm used to naming functions like so:
    Code:
    function name()
    This is how other languages do it, though in some languages the word function is dropped...
    I take it that in Ex. 15 on your site you are saying that more proper way to name them this way:
    Code:
     name = function()
    Like is used in the following:
    Code:
    request.onreadystatechange = function()
    Is it absolutely necessary to name functions this way, or is it just a style preference?

    Last note: I find your examples just a little hard to read, I generally do not:
    Code:
    if(true){
      do this;
      do that;
    }
    I find it more readable to do:
    Code:
    if(true)
    {
      do this;
      do that;
    }
    unless I want to save space:
    Code:
    if(true){do this; do that;}
    This bit I understand is strictly style preference.

    Ex.22:I love that we now have .getFullYear for the Date() object...no more need for a Y2K fixer function that is needed for the .getYear method

    Is using <!-- and // --> for hiding JavaScript from those browsers that cannot handle it deprecated? Though I would imagine that by pulling the JavaScript out into a .js file makes it unnecessary anyways; and feature sensing makes it unnecessary as well.

    Other than general spelling errors, I find your site VERY informative. Thank you for putting it together.

    Sorry, didn't feel like this absolutely required a new thread....
    Last edited by Spidey1980; 01-23-2012 at 05:36 AM.

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,641
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Spidey1980 View Post
    Ex. 9
    Code:
    var name;
    name = window.location.search.substring(1);
    if ('' === name)
    document.getElementById('ex').innerHTML = 'Who are you?';
    else
    document.getElementById('ex').innerHTML = 'Hello '+name;
    So brackets are optional?
    When there is only a single statement in each path there are. The concepts of blocks is introduced in the next example. It does make maintaining the code easier if you always use them.

    Quote Originally Posted by Spidey1980 View Post
    Another question: I'm used to naming functions like so:
    Code:
    function name()
    This is how other languages do it, though in some languages the word function is dropped...
    I take it that in Ex. 15 on your site you are saying that more proper way to name them this way:
    Code:
     name = function()
    Like is used in the following:
    Code:
    request.onreadystatechange = function()
    Is it absolutely necessary to name functions this way, or is it just a style preference?
    Both ways work but there are a few situations where the way I recommend works and the other way doesn't - such as defining the same function differently in the two paths of an if statement.

    Quote Originally Posted by Spidey1980 View Post
    Last note: I find your examples just a little hard to read, I generally do not:
    Code:
    if(true){
      do this;
      do that;
    }
    I find it more readable to do:
    Code:
    if(true)
    {
      do this;
      do that;
    }
    unless I want to save space:
    Code:
    if(true){do this; do that;}
    This bit I understand is strictly style preference.
    Yes. That is simply a matter of which you prefer. Ideally you'd compress all the unnecessary space out of the JavaScript you upload as making the file as small as possible makes it faster to load.


    Quote Originally Posted by Spidey1980 View Post
    Ex.22:I love that we now have .getFullYear for the Date() object...no more need for a Y2K fixer function that is needed for the .getYear method
    getFullYear was the Y2K fix for getYear.


    Quote Originally Posted by Spidey1980 View Post
    Is using <!-- and // --> for hiding JavaScript from those browsers that cannot handle it deprecated? Though I would imagine that by pulling the JavaScript out into a .js file makes it unnecessary anyways; and feature sensing makes it unnecessary as well.
    Feature sensing wouldn't make it unnecessary but making it external does. It is only necessary if you still have visitors who use Netscape 1 or Internet Explorer 2 or earlier browsers than those. Once everyone was using Netscape 2 or IE3 it became completely unnecessary even for inline scripts.

    Quote Originally Posted by Spidey1980 View Post
    Other than general spelling errors, I find your site VERY informative. Thank you for putting it together.
    I thought i'd fixed all the typos in the text (the spelling errors tend to be more due to my managing to hit the wrong key on the keyboard rather than not knowing how to spell).
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    New Coder
    Join Date
    Jan 2012
    Posts
    20
    Thanks
    2
    Thanked 1 Time in 1 Post
    lol so many typos...

    I still love your site though, it has just become my primary resource.
    You have been very helpful here, everyone else was soooo sarcastic in my other threads.
    Thank you again!!
    Last edited by Spidey1980; 01-23-2012 at 07:23 AM.

  • #8
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,641
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Spidey1980 View Post
    lol so many typos...
    I am sure that there are not all that many typos on the pages. Are you sure that you are not getting confused over words that are spelt differently in different countries? I generally use Australian or English spelling on my sites as those are the countries I have spent the most time in.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •