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
.