Jump to content

Recommended Posts

I'm running code to get my returned value via xmlHttp.responseText and it's working fine. However, once I get this value back, I'm trying to do a FOR loop like this...

 

for(var i = 0; i < array.length; i++)
    {
 if(array[i] == xmlHttp.responseText)
             {   //do this } else { // do that }
      }

 

No matter what I do, it's doing the "do that" portion of the code.  I basically just want to check each value in array to see if any of them matches the xmlHttp.responseText EXACTLY.  If so, I want it to "do this."  But again, it keeps "doing that."

 

But an array element DEFINITELY does match the xmlHttp.responseText EXACTLY.

 

Is something wrong with my syntax? Do I maybe need quotes somewhere or should I be using a single equals sign (=), or maybe three equals signs (===)?

 

I think I've tried all scenarios and still can't get it to work, so just figured I'd ask in case I'm missing something obvious.

 

Also, below is the array and the full AJAX function (I didn't include the compare.php file because I am getting the returned value back, so I don't think there is an issue with that part of the code). Maybe I have my FOR loop in the wrong part of the code????...

 


var array=new Array(20);
array[0]="mother";
array[1]="passion";
array[2]="smile";
array[3]="love";
array[4]="eternity";
array[5]="fantastic";
array[6]="destiny";
array[7]="freedom";
array[8]="liberty";
array[9]="tranquility";
array[10]="peace";


function ajaxFunction()
	{

		var userinput=document.getElementById('answerbox').value;


		var xmlHttp;
		try
		  {  // Firefox, Opera 8.0+, Safari  
		  xmlHttp=new XMLHttpRequest();  }
		catch (e)
		  {  // Internet Explorer  
		  try
			{    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    }
		  catch (e)
			{    try
			  {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      }
			catch (e)
			  {      alert("Your browser does not support AJAX!");      return false;      }    }  }
		  xmlHttp.onreadystatechange=function()
			{
			if(xmlHttp.readyState==4)
			  {



for(var i = 0; i < array.length; i++)
    {
if(array[i] == xmlHttp.responseText)
             {   //do this } else { // do that }
      }


}
										  

			  
			}

		  xmlHttp.open("GET","compare.php?userinput=" + userinput,true);
		  xmlHttp.send(null);  
		  

  
		  
	}

First check if your ajax call is actually returning anything, remove the for loop and just have an alert() which is a messagebox popup like:

 

alert(xmlHttp.responseText);

 

Run the code and if nothing is alerted, then there is a problem with your ajax function.

 

Also I would suggest you change your array name because having it called "array" could be causing you problems now or in future.

 

If you see the data alerted, just create a function that will take the data as an argument, and call it when there is some responseText, then put the for loop in there.

Here is the compare.php file.  All it's doing is seeing if what the user enters matches something exactly.  I only have it checking against two answers right now, because I want to get it working first before I have it checking for ALL answers....

 


<?php
require_once("includes/session.php");
require_once("includes/connection.php");

$userinput = $_GET['userinput'];

if ($userinput == 'mother' || $userinput == 'mom') {

	 echo "mother";

} else if  ($userinput == 'passion') {

		echo "passion";

} else {

//do nothing
}


?>


I wasn't sure exactly where to put that alert, but I threw it in after the { sign after the FOR loop (hope that was right) so it looked like what you see in the code box below.  But to answer your question, after I added the alert, it DID pop up an alert box as soon as I typed the first character in my answer field that said the first word in the array, then I hit OK and it showed the next one, then I hit OK and it showed the next one, and so on until it showed all the words in the array.  So I think that means, yes it did alert correctly, but I could be wrong because I'm just too damn new to javascript :)...

Anymore thoughts?

 

 

for(var i = 0; i < beautifulWords.length; i++) 
							{ window.alert(array[i] + " " + xmlHttp.responseText);
							  if(beautifulWords[i] === xmlHttp.responseText)
							  { 
								document.getElementById('answer'+i).style.display = "block";

Also, I put the alert in like the182guy said and it does do the alert on every keystroke (not sure if I mentioned this before, but I call the AJAX function on "onKeyUp").  So even though my compare.php file is looking for user input of "mother", as soon as I type "m", it pops open a blank alert window. 

Is there a way to prevent the xmlHttp.responseText from sending anything back UNLESS it matches the word "mother" exactly?  I think the fact that it sends a black xmlHttp.responseText until it finds a match could be causing some of the problem.

Well it just has an alert box that says "mother" and an OK button. I hit OK and it immediately opened another alert box that says "passion" and an OK button.  And so on until I hit OK for each work.

 

I just tried to do this...

 

if (xmlHttp.responseText !== "") {
					alert(xmlHttp.responseText);

 

But as soon as I press the first key, it opens a blank alert window. So I thought my code was saying, "If the xmlHttp.responseText is NOT blank, then do the alert" but since it did the alert anyway and showed NOTHING, then I must have some wrong syntax.  Any idea?

(Fyi, I know I'm jumping all over the place here, but I think if I can get the xmlHttp.responseText to NOT come back on every single key stroke, that would get me closer to where i need to be, if not all the way there.

I had named it "array" in my first basic example, but it actually is called "beautifulWords."  And the words in that array are mother, passion, smile, etc, etc.  Maybe I'm misunderstanding when you say "post the alerts" but again, all that happens is it pops up an alert box that says "mother" with an OK button.  Then another pops up that says "passion" with an OK button. And so on until it alerts all the words in the beautifulWords array.

 

If you mean something else by "post the alerts", let me know.

I think this is everything you wanted.  Sorry, if this doesn't help, I should probably just get the hint that I just don't know enough yet to even be asking questions about it:)..

 

The whole gist is that users are asked to guess the 20 most beautiful words and they enter their guesses one at a time into the text field. Their guess is sent to compare.php via AJAX and if it matches an acceptable answer (i.e. mother or mom is acceptable for mother), then it spits back the word via xmlHttp.responseText.

 

Then I want to do the FOR loop that loops through the beautifulWords array until it finds the word in the array that matches xmlHttp.responseText EXACTLY, and then it reveals that word lower down on the screen with a green background...

 

The HTML where user enters their "guess" into the text field...

 

<div id='answerfield' style='display: none;'>
            Enter answer: <input id="answerbox" type="text" size="30" onKeyUp='ajaxFunction();' name="userinput"><br />
            See returned value: <span id="compareresults"></span>

 

 

Javascript....

 


function ajaxFunction()
	{

		var userinput=document.getElementById('answerbox').value;


		var xmlHttp;
		try
		  {  // Firefox, Opera 8.0+, Safari  
		  xmlHttp=new XMLHttpRequest();  }
		catch (e)
		  {  // Internet Explorer  
		  try
			{    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    }
		  catch (e)
			{    try
			  {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      }
			catch (e)
			  {      alert("Your browser does not support AJAX!");      return false;      }    }  }
		  xmlHttp.onreadystatechange=function()
			{
			if(xmlHttp.readyState==4)
			  {

				document.getElementById('compareresults').innerHTML = xmlHttp.responseText;

					if (xmlHttp.responseText !== "") {
					alert(xmlHttp.responseText);
					var returnvalue = xmlHttp.responseText;
						for(var i = 0; i < beautifulWords.length; i++) 
							{ 
							  if(beautifulWords[i] == returnvalue)
							  { 
								document.getElementById('answer'+i).style.display = "block";
								document.getElementById('answer'+i).innerHTML = beautifulWords[i];
								document.getElementById('answer'+i).style.background ="green";

								//increase total # correct and display it on the screen
								numbercorrect++;
								document.getElementById('numbercorrect').innerHTML = numbercorrect;
								//wiping out the text field so it's ready for a new guess
								document.getElementById('answerbox').value = "";


								beautifulWords[i] = beautifulWords[i] + " ";


									if (numbercorrect == totalanswers) {
									document.getElementById('answerfield').style.display ="none";
									document.getElementById('gotemall').style.display ="block";
									document.getElementById('timer').style.display ="none";
									if (timeoutObj) clearTimeout(timeoutObj);
									} else {
									}

							  } else {
							  
							  }
							}
						}


				}
										  

			  
			}

		  xmlHttp.open("GET","compare.php?userinput=" + userinput,true);
		  xmlHttp.send(null);  
		  

  
		  
	}

The compare.php PHP file...

 


<?php
require_once("includes/session.php");
require_once("includes/connection.php");

$userinput = $_GET['userinput'];

if ($userinput == 'mother' || $userinput == 'mom') {
	 echo "mother";

} else if ($userinput == 'passion') {
		echo "passion";
} else {

}

?>





We have a bit of cleaning up to do.

 

Replace all your files with these respectively. I can only go by what I see, so forgive me if I'm adding something you already have.

 

<div id='answerfield' style='display: none;'>
            Enter answer: <input id="answerbox" type="text" size="30" onKeyUp="ajaxFunction(this.value);" name="userinput"><br />
            See returned value: <span id="compareresults"></span>
</div>

 

 

function ajaxFunction(val) {
var xmlHttp;
try {  // Firefox, Opera 8.0+, Safari 
	xmlHttp=new XMLHttpRequest();
} catch (e) {  // Internet Explorer 
	try {
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			alert("Your browser does not support AJAX!");
			xmlHttp=null;
		}
	}
}
if (xmlHttp !== null) {
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4 && xmlHttp.status==200) {
			var response = xmlHttp.responseText;
			alert(response);
		}
	}
	xmlHttp.open("GET","compare.php?userinput=" + val,true);
	xmlHttp.send(null);
}
}

 

<?php
$userinput = strval($_GET['userinput']);

switch ($userinput) {
     case 'mom':
     case 'mother':
          echo 'mother';
          exit;
     case 'passion':
          echo 'passion';
          exit;
     default:
          echo 'random';
}

 

This time when you run it, do you get a pop up? Also, where's your beautifulWords array? You didn't include it. By the way, this is for debugging what's wrong. Bare with me as we take simple steps. Your code was a big mess so it is too hard to debug it.

Ok Ken, I used your files and I get an alert pop-up as soon as I start typing that keeps popping up "random" until I eventually am able to type either "mother" or "mom" or "passion" (then it alerts the word "mother" or "passion" accordingly).

 

I think I'm kind of at the same point I was before (albeit with cleaner code, thank you) because I have always been at the point where I can get these alerts to pop-up as I type. 

 

My whole thing is that I just want to be able to get the XMLHttp.responseText value into a variable and cycle it through a for loop, looking for an EXACT match to ANY of the words in the beautifulWords array (which is listed below). 

 

-If the responseText does NOT match any of the words EXACTLY, then I don't want anything to happen.

-If it DOES match one of the words exactly, then I have other stuff that will happen (like displaying the value in another part of the page, changing color backgrounds of it, etc) all of which, believe it or not, I can handle.

 

I just can't find the right way to use the responseText that is sent back from compare.php to cycle it through a for loop which looks for an EXACT match with any of the words in the beautifulWords array. 

 

Also, here's the array...

 

var beautifulWords=new Array(20);
beautifulWords[0]="mother";
beautifulWords[1]="passion";
beautifulWords[2]="smile";
beautifulWords[3]="love";
beautifulWords[4]="eternity";
beautifulWords[5]="fantastic";
beautifulWords[6]="destiny";
beautifulWords[7]="freedom";
beautifulWords[8]="liberty";
beautifulWords[9]="tranquility";
beautifulWords[10]="peace";
beautifulWords[11]="blossom";
beautifulWords[12]="sunshine";
beautifulWords[13]="sweetheart";
beautifulWords[14]="gorgeous";
beautifulWords[15]="cherish";
beautifulWords[16]="enthusiasm";
beautifulWords[17]="hope";
beautifulWords[18]="grace";
beautifulWords[19]="rainbow";

Change just the JavaScript part to this:

 

var beautifulWords=new Array("mother", "passion", "smile", "love", "eternity", "fantastic", "destiny", "freedom", "liberty", "tranquility", "peace", "blossom", "sunshine", "sweetheart", "gorgeous", "cherish", "enthusiasm", "hope", "grace", "rainbow");

function ajaxFunction(val) {
   val = val.toLowerCase();
   var xmlHttp;
   try {  // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
   } catch (e) {  // Internet Explorer
      try {
         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {
            alert("Your browser does not support AJAX!");
            xmlHttp=null;
         }
      }
   }
   if (xmlHttp !== null) {
      xmlHttp.onreadystatechange=function() {
         if(xmlHttp.readyState==4 && xmlHttp.status==200) {
            var response = xmlHttp.responseText;
            for (var e = beautifulWords.length; --e > -1 ) {
                 if (response == beautifulWords[e]) {
                      alert("Match");
                 }
            }
         }
      }
      xmlHttp.open("GET","compare.php?userinput=" + val,true);
      xmlHttp.send(null);
   }
}

 

That should echo "Match" if you type the word correctly. Case-insensitive too.

 

P.S.: You don't need to put a restriction on the number of entries in your array. If you don't specify 20, you can do as much as you want. I also shorten the typing.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.