Jump to content

Recommended Posts

Hello:

 

I am trying to place a word that is chosen from a dictionary file chosen by using AJAX into another variable.

 

The random word is selected in a .php file and retrieved with AJAX techniques.

It is then placed into the xmlhttp variable.

 

However i want to get it to work for when the "Start" button is clicked...the new game function is called, but the 'm' variable get's it's data from myfunction() where it calls the AJAX request.

 

Any help would be great.

 


<HEAD>

<SCRIPT LANGUAGE="JavaScript">


var gameWord;
var len=gameWord.length - 1;
var xmlhttp;
var m;
function myfunction()
{
   //variable to hold the word from the server
  if(window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest();
  }
  else 
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    
  }
  
  xmlhttp.onreadystatechange=function()
  {
      if(xmlhttp.readyState==4)
      {
        gameWord=xmlhttp.responseText;
        
        
        
      }
  
  } 

  xmlhttp.open("POST", "get_word.php", true);
  xmlhttp.send(null);
}


function newGame()
{

var badGuess="0";
var IntialInput="";
var x= new Array();

space=/ /g;

myfunction();
m=gameWord;
sweep();
diplayPattern(IntialInput);
countRemain(badGuess);
document.myForm.input.focus();
  
}

function diplayPattern(inputChar){

var pattern =" ";
  for (i=0; i < m.length; i++)
  {
if (m.charAt(i) == " ")
{
	pattern += "  ";
}
else if (inputChar.indexOf(m.charAt(i).toUpperCase()) != -1)
{
	pattern += m.charAt(i).toUpperCase() + " ";

}
	else pattern += "_ ";
  }
document.myForm.toGuess.value=pattern;
}



function renameBut(myValue){

  
sweep();
}

function sweep(){
for (i=0; i < document.theDetails.length - 1; i++)
{ document.theDetails.elements[i].value="";}

for(i=3; i!=6 && i < document.myForm.length; i++)
{document.myForm.elements[i].value=""}

document.myForm.counter.value="";
}

function winner(){
  if (document.myForm.toGuess.value.indexOf("_ ") == -1) return true;
}

function displayDetails(){

  for(i=0; i < gameWord.length; i++)
  { 	if (m == gameWord[i][0] )
{
	alert("You won. You are Genius!\n\n"+ "' " +m + " '    ' " + gameWord[i][1]+ " '");
	for (j=0; j< gameWord[i].length ; j++)
	{
document.theDetails.elements[j].value=" " + gameWord[i][j];
	}
	}
    	else if (m == gameWord[i][1])
{
	alert("You won. You are Genius!\n\n"+ "' " +m + " '    The Capital City is   ' " + gameWord[i][0]+ " '");
	for (j=0; j< gameWord[i].length ; j++)
	{
document.theDetails.elements[j].value=" " + gameWord[i][j];
	}
}
  }
}

function countRemain(num){

myMatch=m.match(/\w/g);
returnWord=m.match(/(\w|\s)/g);

  if   (m.match(space) == null) {space_YorN=m.length;}
  else {space_YorN= m.length - m.match(space).length;}
document.myForm.counter.value=space_YorN - (num.length-1) / 2;
  if (space_YorN - (num.length-1) / 2 <= "0")
  {
alert("Oops! you lost. The word you missed is: \n\n   \"" + m.toUpperCase() +"\"" );		document.myForm.toGuess.value=" ";
for (i=0; i < m.length; i++)
{
	document.myForm.toGuess.value += returnWord[i].toUpperCase() + " ";
}
  }
}

function makeAGuess(){
var indx= new Array("a","b")
var myInput=document.myForm.input.value.toUpperCase();
var cc=" ";
  else
  {
if (!document.myForm.toGuess.value)
{
	alert("Click on \"" +document.myForm.start.value +"\" Button.");
	}else
  	{
	diplayPattern(myInput);
	document.myForm.input.focus();
	if (!document.myForm.input.value)
	{
		alert("Guess a letter.")
	}else
	{
		if ((myInput.substring(0,myInput.length-1)).indexOf(myInput.charAt(myInput.length-1)) != -1)
		{
		alert("You already used << "+myInput.charAt(myInput.length-1)+ " >> \n Make another guess.");
		myInput=myInput.substring(0,myInput.length-1);
		document.myForm.input.value=myInput.toLowerCase();
		}
		for (i=0; i<myInput.length; i++)
		{
  			if (m.toUpperCase().indexOf(myInput.charAt(i)) == -1) {cc +=myInput.charAt(i) + " ";}

		}


		if (winner())
		{
			displayDetails();
		}
	}
document.myForm.guessed.value=cc.toUpperCase();
countRemain(cc);
}
  }
}
//  End -->
</script>

</HEAD>



<BODY onLoad="document.theDetails.gameLength.value=guessChoices.length;">


<div align=center>
<table border=0 cellpadding=3>
<tr>
  <td  valign=top align=center><font size=7 face="arial black"><center>Lingo</center></font>
  
   <table border=0 cellpadding=9 cellspacing=0 bordercolor="black" bgcolor="#ffffc6" width=290>
    <form name="myForm">
<tr>
     
      </tr>
     </table><br> <div align=left>

<font size="2" color="#685dab">Get A New Word</b></font><font size="2"><input type="button" name="start" value="Get New Word" onClick="newGame();"><p>
<font size="3" face="arial"><center><input type="text" size="43" name="toGuess" readonly><br>
<input type="text" name="guessed" size="43" readonly></center></font>

<table><tr><td align=left>
<font size=2 color="#685dab">

</font>
</td></tr></table>

<font size=2 color="#685dab"><b>c- </font><font size=3><input type="text" name="input" size=35></font> <input type="button" value="Submit Guess" onClick="makeAGuess();"><br> <!---->
<div align=left>
<font size=2 color=red></font> <font size=1 color="#000000"><i>You only have </i></font><font size=3 face=arial><input type="text" name="counter" value="" size=2 maxlength=2 disabled></font><font size=1 color="#000000"><i> bad guess before you lose!.</i></font>
</form>

    </td></tr>
    <tr><td align=center  valign="top">

    </td>
  </tr>
</table>

</td>
</tr>
</table>

It's kinda hard to read through that much code to see the issue, but I have to say posting too much code is better than not enough.

 

My first thoughts are that the JS is running very quickly, and it doesn't wait for the AJAX to finish. You have your onreadystatechange function that sets gameWord, but your JS is setting m to equal gameWord before that state has a chance to get to 4. I bet if you run it over and over, waiting a few seconds each time, you'll actually get the previous response each time.

You really should keep the onreadystatechange function. But, maybe combine more stuff into that function. I didn't read enough of your code to know exactly what you're doing with that data, but really you don't want to assume that variable is set before it is.

 

I have a couple thoughts: You could remove the onreadystatechange function and just simply do the gameWord=xmlhttp.responseText; assignment. The problem with that is that the browser will essentially freeze until that's done, which technically isn't true AJAX, but it will set your variable properly, because it won't allow any further JS to run until it's done. You could also set a flag before you make the AJAX call and do a while function or something until it is reset, which you would reset inside the onreadystatechange function, however this will also lock the browser until it's complete.

 

These are simple solutions, although not ideal. What you really need to do is re-write your XMLHttpRequest stuff so that it is better integrated with exactly what you need to do. For instance, you could write another function that creates an XMLHttpRequest object, then insite the onreadystatechange function and in the if (state == 4), write the rest of what you want the code to do. This will wait until the AJAX is done running before it continues the rest of the JS code, thus ensuring that you get the variable you're looking for.

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.