Ecco un'alternativa con AJAX ma non jQuery, solo JavaScript normale:
Aggiungilo alla prima / principale pagina php, da cui vuoi chiamare l'azione, ma cambialo da un potenziale a
tag (collegamento ipertestuale) a un button
elemento, in modo che non venga cliccato da nessun bot o app dannose (o altro).
<head>
<script>
// function invoking ajax with pure javascript, no jquery required.
function myFunction(value_myfunction) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML += this.responseText;
// note '+=', adds result to the existing paragraph, remove the '+' to replace.
}
};
xmlhttp.open("GET", "ajax-php-page.php?sendValue=" + value_myfunction, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php $sendingValue = "thevalue"; // value to send to ajax php page. ?>
<!-- using button instead of hyperlink (a) -->
<button type="button" onclick="value_myfunction('<?php echo $sendingValue; ?>');">Click to send value</button>
<h4>Responses from ajax-php-page.php:</h4>
<p id="results"></p> <!-- the ajax javascript enters returned GET values here -->
</body>
Quando si button
fa clic su, onclick
utilizza la funzione javascript della testa per inviare $sendingValue
tramite ajax a un'altra pagina php, come molti esempi prima di questa. L'altra pagina ajax-php-page.php
verifica il valore GET e restituisce print_r
:
<?php
$incoming = $_GET['sendValue'];
if( isset( $incoming ) ) {
print_r("ajax-php-page.php recieved this: " . "$incoming" . "<br>");
} else {
print_r("The request didn´t pass correctly through the GET...");
}
?>
La risposta da print_r
viene quindi restituita e visualizzata con
document.getElementById("results").innerHTML += this.responseText;
Il +=
popola e aggiunge agli elementi html esistenti, rimuovendo gli +
aggiornamenti giusti e sostituisce i contenuti esistenti p
dell'elemento html"results"
.