search

Home  >  Q&A  >  body text

Pass arguments to a specific function in a PHP file on the server side (from JS) and return the result to the JS function that called the function

Basically what I'm doing is creating a graphing calculator (using BokehJS) that currently takes some input via html, then javascript reads the data and does the calculations, then outputs the resulting graph.

The problem is that we don't want users to be able to see all the calculation code. It would be nice if they could see the getter and setter methods.

What I need it to do is:

  1. Get user input on HTML page
  2. Read input using JavaScript (client side)
  3. Pass the read input data to PHP (on the WordPress server) for calculation
  4. PHP sends result data back to JS
  5. JS (client side) handles what to do and how to display the data

We are using a WordPress server and currently I am only testing on my local machine so a way to allow testing and deployment would be great.

Currently this is what I have:

myjavascript.js

function test_test(){

    const staticPNVals = getStaticPN(); //send this to php file as parameter to function
    const ret_array = [];
    
    //The below needs to be changed, idk how to do it
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
        const myObj = JSON.parse(this.responseText);
        ret_array = myObj;
    }
    xmlhttp.open("GET", "test.php");
    xmlhttp.send();

    console.log("ret_array is " + ret_array);
}

test.php

<?php
function doStuff($myarr) {
    $myarr2 = array();
    for ($x = 0; $x <= 10; $x++) {
        array_push($myarr2, $myarr[$x]);
      }
    return $myarr2;
}

function doOtherStuff(){
    echo "Hello World";
}
?>

I would like to have it so I can have multiple functions in one file, most solutions I see only have 1 function in each file.

mypage.html

<!-- Just a simple button to call the main Javascript function-->
<input type="button" value="Test function" onclick="test_test()">

So basically, the overall question is how do I change the javascript request to be able to pass parameters to server side PHP and then back to calling the js function

EDIT: It would be nice if there was a way to use server side javascript instead of PHP, since the script is already written in JS and I don't want to rewrite it in PHP unless necessary.

P粉593649715P粉593649715322 days ago471

reply all(1)I'll reply

  • P粉129168206

    P粉1291682062024-01-17 12:15:40

    How I solved a similar problem JS

    let formData = new formData();
        formData.append("nameOfFunction","function you want to call");
        formData.append("variableA","some value");
    fetch("phpFileName.php"{body: formData,method: POST})
        .then((response)=>response.text)
        .then((data)=>{
            //do whatever
        })

    PHP

    $nameOfFunction = $_POST["nameOfFunction"];  // unsure past this point
    echo "