First, you can’t do it, at least not directly. That’s because PHP code never makes it to the client and Javascript executed on the client rather than on the server. What is needed is a way to bridge the two. For that you can thank the AJAX principle – doing remote HTTP requests.

I’m not going to provide a functional example but rather an outline that you can use get the job done. The accompanying code snippets will help you accomplish your goal.

Let’s say in you have a <div> where you want to place the PHP output. No problem. Just give it the desired ID.  <div id=myPHPtarget></div> would get the job done.

Then make the call with the HTTP request, get the results, and place them in the div.

But from where would you call getWhatIsNeeded()? You might call it from any onChange or onClick event. Perhaps from a selection button. In any case you can modify the code to pass parameters to it so that you can, as needed, modify the whatToExecute for these parameters.

function getWhatIsNeeded() {
var xhttp = new XMLHttpRequest();
// depending on the data your’re working with just calling your routine may suit your needs
// At other times, perhaps based on a user selection, you’ll have to append command line
// parameters to this.
var whatToExecute = “mycode.php”;

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“myPHPtarget”).innerHTML = this.responseText;
};“GET”, whatToExecute, true); xhttp.send();

What you have is a solution for calling PHP from Javascript. The client is making a request of the server. Hopefully this will get you started toward completing your solution.