0

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);
        });
    });
});
J. Doe
  • 63
  • 9

2 Answers2

0

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
}
});
Mike Aron
  • 550
  • 5
  • 13
  • I don't want to iterate through the array of words but rather just check if the word gotten from the database is in the array of words and if it is, to request a new word. – J. Doe Nov 22 '16 at 18:02
  • Here its answered and explained: http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript – Mike Aron Nov 23 '16 at 18:09
  • Take a look at jQuerys: jQuery.inArray() – Mike Aron Nov 23 '16 at 18:10
0

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 :)