3

I am creating a web page where someone can visit it. They type a question in a field and click a button, and a response is passed back to them. (Kind of like a magic 8 ball).

What I'm trying to do is set it up something like this:

http://img585.imageshack.us/img585/997/layoutoi.png

I'm still new to hand-coding things - I have a book on HTML/CSS and one on PHP, which lay still unread, so I'll probably need a step-by-step process. (I have a host and everything, so that's already taken care of.) Thanks in advance!

0

3 Answers 3

3

To do it without a page load (i.e. immediately after the button click), you'll have to do it in Javascript (working jsfiddle example here)

<a id="myButton" href="#">
    click here to get random stuff
</a>

<div id="myRandomDiv">
</div>

<script type="text/javascript" charset="utf-8">
    var randomStrings = [
        "hello 1",
        "hello 2",
        "hello 3", 
        "hello 4",
        "hello 5",
    ];



    var randomDiv = document.getElementById("myRandomDiv");

    document.getElementById("myButton").addEventListener("click", function() {
          randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
          newText = randomStrings[randomIndex];
          randomDiv.innerHTML = newText;
    });
</script>    

To do this instead in PHP (which will require a new page load), you could do this:

<?php


$randomThings = array(
    'random thing 1',    
    'random thing 2',    
    'random thing 3',    
    'random thing 4',    
    'random thing 5',    
    'random thing 6',    
    'random thing 7 ',    
);

?>




<!-- REST OF YOUR PAGE -->

<?php

echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>

<!-- OTHER STUFF -->

First, we create an array ('list') of random things and store it in the variable $randomThings.

Elements in an array can be accessed using $variableName[$index] -- in this case, the indices will simply be 0,1,2,3,4,5,6.

The reason this one-liner (beginning with 'echo') works is, mt_rand is going to return a random number between 0 and 6, so it'll grab a random element from the $randomThings array. echo will then spit it to the page.

5
  • That should be count($randomThings) - 1 as mt_rand() is inclusive. Commented Jan 19, 2011 at 1:44
  • 1
    Thanks for the answers all of you guys (and gals!). I have two quick questions - sometimes, I get "undefined" as a result when I click "myButton". Is there a way around this or will it just happen sometimes? Also, would all of this code go into one page or would it be divided into multiple pages? For example, in Dreamweaver, on the page with the content for the site, do I post the HTML and Javascript, or just HTML and create a separate file for the Javascript itself? Sorry, like I said before, new to the whole coding-by-hand scene. :D Commented Jan 19, 2011 at 4:46
  • Sorry about that error, BigCaseyDog. That was happening on the JS Fiddle because I linked an outdated version from when I was experimenting. I've fixed it now :)
    – Kyle Wild
    Commented Jan 19, 2011 at 8:21
  • You could put this all on one HTML page by surrounding the javascript in script tags as I've done here, or you could the javascript in a JS File: hypergurl.com/jsfiles.html
    – Kyle Wild
    Commented Jan 19, 2011 at 8:22
  • Oh, ok, thanks for the link - that explained everything. Thanks so much all of you for everything - it works like a charm! I'll post again if I have any more questions! Commented Jan 19, 2011 at 15:44
3

Dorkitude's answer is a fine example but just as an additional bit of advice I would like to point out that it is usually considered bad practice to hard code data inside your scripts (i.e. $value = 'someValue') unless there is absolutely no other way around it. Instead you would use some kind of data source for your responses instead (plain text file, database, web service etc).

For example lets say you have stored your list in a plain text file called 'randomThings.txt' and placed each response on its own line. You could then adapt Dorkitude's code like so:

<?php
    // Flags set here to ensure integrity
    $randomThings = file('responses.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

<!-- REST OF YOUR PAGE -->

<?php

    echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>
<!-- OTHER STUFF -->
1
  • Thank you, I was wondering this, the only bit I'm stuck on is the syntax to make an array out of multiple files. I've tried using $array4 = $array1 + $array2 + $array3; $sentence = $array4[mt_rand(0, count($array4) - 1)]; return $sentence; But it only outputs the first array.
    – GibsonFX
    Commented Jun 18, 2017 at 6:37
2

I know you tagged the question PHP, but you might want to consider using javascript instead. The advantage is that you won't need to reload the page - for something this simple, there isn't really any advantage to using php.

A javascript solution would look something like this:

<html>
  <head>
    <script type='text/javascript'>
      var answerArray = new Array("yes", "no", "maybe");

      function getAnswer() {
        document.getElementById('answerDiv').innerHTML = 
          answerArray[Math.floor(Math.random() * answerArray.length)];
      }
    </script>
  </head>
  <body>
    <input id='questionField' type='text' /><br/>
    <input type='submit' value='Ask Me!' onclick='getAnswer()' />
    <div id='answerDiv'></div>
  </body>
</html>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.