I have a php file that gets a word from a database randomly and json encodes it. I want to get the word using jquery but also make sure that word isn't in a list already. I'm confused on how I can repeatedly hit the server till my condition is met. Here is what I have:
php:
<?php
$sql = "SELECT * FROM words ORDER BY RAND() LIMIT 1";
$result = $db->query($sql);
$row = $result->fetch_assoc();
$word = $row['word'];
echo json_encode($word);
?>
Jquery function:
$(document).ready(function() {
$("#newRound").on("click",function(){
$.getJSON("getWord.php",function(data){
//check here if data is already in wordsSoFar arary and if it is, get another word from getword.php
document.getElementById("input1").style.visibility = 'visible';
currentWord = data; //set the current work
lives = 6; //reset lives
tracker = 0;
incorrectLettersGuessed = "";
allGuessedLetters = "";
updateLetters();
document.getElementById('hangman').innerHTML = '<center><img src="stage1.png"></center>';
createTable(currentWord);
output.innerHTML = '<center>'+messages.validLetter + '</center>';
alert(currentWord);
});
});
});
if you want a sql solution:
$sql = "SELECT * FROM words WHERE column_name NOT IN ('yourword1','yourword2','youword3'...) ORDER BY RAND() LIMIT 1";
EDIT: i saw your comment too late (Check it on client side).
here a jquery solution (because youre working with jQuery):
$.each(yourwordsarray, function( index, value ) {
if(value == word_is_in){
.. do what you want with the word
}
});
Save the words which the database already gave you in another table then just check if the new word is not on that table. That table could also have an userID to identify the words which the database gave you to that user and a datetime column to check the date when the user play your game, so you could repeat words from past days. It's better if you validate this on your database :)