Hi. Welcome to Bytes!
As you say, mixing JavaScript and PHP in the way you do is not possible, JavaScript being executed on the client browser while PHP is executed on the server.
From PHP's point of view, there is no difference between HTML or JavaScript, or even Images or binary data for that matter. It's all just output.
The best way to have JavaScript call PHP directly would be to use AJAX.
An AJAX request would be able to call a PHP page on the server, get it's response, and print it directly to the page, without ever having to refresh or redirect.
Consider this example.
-
# File: rand.php
-
<?php
-
echo mt_rand(0, 100);
-
?>
-
-
# File index.html
-
<html>
-
<head>
-
<script type="text/javascript">
-
function GetRandom() {
-
// Create and initialize xmlHttpRequest
-
var request = null;
-
-
if (window.XMLHttpRequest) { // Mozilla/Safari
-
request = new XMLHttpRequest();
-
}
-
else if (window.ActiveXObject) { // IE
-
request = new ActiveXObject("Microsoft.XMLHTTP");
-
}
-
-
// Define how to handle the response
-
request.onreadystatechange = function() {
-
// Readystate 4 means it's been received
-
if (request.readyState == 4) {
-
document.getElementById('outputBox').innerHTML = request.responseText;
-
}
-
}
-
-
// Send the request
-
request.open("GET", "rand.php", true);
-
request.send(null);
-
}
-
</script>
-
-
</head>
-
-
<body>
-
<div id="outputBox">Nothing fetched yet</div><br />
-
<button onclick="javascript: GetRandom();">Get randon number</button>
-
</body>
-
</html>
-
This just has the JavaScript code send a AJAX request for "rand.php", and prints the result of that into the <div>.
It's pretty useless as such, but you get the picture.