Search code examples
javascripthtmlrandomgeneratorphrase

Random Sentence generator in HTML / JavaScript


I'm looking to build a simple mini site with a random sentence generator. That when the visitor clicks a button the site display a random phrase that is taken from a database of phrases.

And if its possible a second mini site that lets the users add their own phrases for the database that is going to be used for the first mini-site.

I'm still new in hand-coding things, but I'm working hard on it

Something like this:
First site: First site
Second site: Second site


Solution

  • Using php and javascript I created 2 files.

    • call.php - Retrieves a sentence from a database and prints one of them (Random)
    • index.html - A page with a button that runs a function which retrieves a sentence from call.php

    call.php:

    <?php
    $db_host = "localhost"; //Host address (most likely localhost)
    $db_name = "DATABASE_NAME"; //Name of Database
    $db_user = "DATABASE_USERNAME"; //Name of database user
    $db_pass = "DATABASE_PASSWORD"; //Password for database user
    $mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
    
    $stmt = $mysqli->prepare("SELECT sentence
                    FROM `table_sentences`
                    "); //gets all the values in the column "sentence" from the table `table_sentences`
    $stmt->execute(); //Execute the query
    $stmt->bind_result($sentence); //Bind the results into array
    $array = array(); 
    while ($stmt->fetch()){
        array_push($array,$sentence); //enter each sentence, in to the array ($array)
    }
    $stmt->close(); //Close the connection
    
    $rand = array_rand($array, 1); //Random one value from the array
    
    echo $rand[0]; //Echo the value
    

    index.html:

    <html>
    <head>
    <script>
    function getSentence() { //defines a function named getSentence
        var xhr = new XMLHttpRequest(); //creating a new request
        xhr.open("get", "call.php", true); //setting the file to get the data from
        xhr.onload = function(){
            var response = xhr.responseText; //Save the sentence into a var
            document.getElementById("text").innerHTML = response; //Set where the sentence should display
        }
        xhr.setRequestHeader('Cache-Control', 'no-cache'); //Prevent caching
        xhr.send(null); //Submit the request
    }
    </script>
    </head>
    <body>
    <p id="text"></p>
    <button onClick="getSentence()">Get Sentence</button>
    </body>
    </html>