Random word generator with end

0

I'm working on a random word generator, I've made a word appear every time I press a button:

    <?php
     $frases = array(
     1 => "Una lavadora",
     2 => "Un movil",
     3 => "Una muñeca",
     );

     $numero = rand (1,3);

     echo "$frases[$numero]";
      ?>
      <input type="button" value="iniciar" onclick="document.location.reload();">    

1-How can I do so that the third time I press the button, the word HAS PULSEED THREE TIMES THE BUTTON! and stop generating words?

2-Is there any way to do it without reloading the whole page?

    
asked by Antonio Ángel Estrada Pérez 04.02.2017 в 12:54
source

2 answers

3

Adding only one counter and asking for the word for AJAX.

PHP     

$frases = array(
  1 => "Una lavadora",
  2 => "Un movil",
  3 => "Una muñeca",
);

$numero = rand (1,3);

echo $frases[$numero];

HTML

<div class="word">
  <span id="wordOutput></span>
</div>
<button id="randomWordGen">Generate</button>

JS

document.addEventListener('DOMContentLoaded', function () {
  var clickTimes = 0;
  var btnRandomWord = document.getElementById('randomWordGen');
  var wordOutput = document.getElementById('wordOutput');

  btnRandomWord.addEventListener('click', function () {
    if (clickTimes < 3) {
      var request = new XMLHttpRequest();
      // método HTTP y URL
      request.open('GET', '/randomwordgen.php');
      request.onload = function () {
        // estado 4 = petición completada y respuesta recibida
        if (request.readyState === 4) {
          // código HTTP 200 = petición exitosa
          if (request.status === 200) {
            wordOutput.textContent = request.responseText;
            clickTimes++;
          }
        }
      };
      request.send(); // se envía la petición
    } else {
      wordOutput.textContent = 'Has superado el límite palabras';
    }
  });
});

The above will work only while the document is not reloaded, if it is recharged, it will have its three words. In case you want it to be while the user has a session, you can use a cookie instead or a better one. sessionStorage .

    
answered by 04.02.2017 / 13:30
source
0

Another way to do it:

PHP

<?php
// definimos un array de valores en php
$arrayPHP = array(
 0 =>"Una lavadora",
 1 => "Un movil",
 2 => "Una muñeca",
 );
?>

HTML

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <p id="demo">Palabra!</p>
    <input type="button" value="iniciar" onclick="print()"> 
</body>

JavaScript

<script type="text/javascript">
// obtenemos el array de valores mediante la conversion a json del
// array de php
var arrayJS=<?php echo json_encode($arrayPHP);?>;

// Establecemos el valor minimo y maximo del array.
var max = <?= count($arrayPHP)-1 ?>;
var min = 0;
//Contador para controlar las pulsaciones del usuario.
var contador = 1;

function print() {
    var ind= randomIntFromInterval(min,max);
        if(contador <= 3) {
            document.getElementById("demo").innerHTML = arrayJS[ind];
            contador++;
        } else {
            document.getElementById("demo").innerHTML = "Ha llegado al maximo";
        }
}
//Genera numeros aleatorios entre un rango dado por parametro.
function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

We convert a PHP object to JavaScript using var arrayJS=<?php echo json_encode($arrayPHP);?>; .

I had a problem converting the object and it is that the index of the array in php should start at 0.

    
answered by 04.02.2017 в 20:03