Here´s an alternative with AJAX but no jQuery, just regular JavaScript:
Add this to first/main php page, where you want to call the action from, but change it from a potential a
tag (hyperlink) to a button
element, so it does not get clicked by any bots or malicious apps (or whatever).
<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>
When the button
is clicked, onclick
uses the the head´s javascript function to send $sendingValue
via ajax to another php-page, like many examples before this one. The other page, ajax-php-page.php
, checks for the GET value and returns with 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...");
}
?>
The response from print_r
is then returned and displayed with
document.getElementById("results").innerHTML += this.responseText;
The +=
populates and adds to existing html elements, removing the +
just updates and replaces the existing contents of the html p
element "results"
.