1

I have a PHP file contain some calculation. Now, I want to integrate the calculation into javascript in another file. How i can pass the variable in javascript to do calculation inside php?

this is my javascript code:

 $("#upload").on("click", function(){
    var csv = $('#csv');
    var csvFile = csv[0].files[0];
    var ext = csv.val().split(".").pop().toLowerCase();

    if($.inArray(ext, ["csv"]) === -1){
        alert('upload csv');
        return false;
    }
    if(csvFile != undefined){
        reader = new FileReader();
        reader.onload = function(e){

            csvResult = e.target.result.split(/\r|\n|\r\n/);
            
            var temp=[];
            for(i=0;i< csvResult.length; i++){
                if(csvResult[i] != "" && csvResult[i] != null){
                var data = csvResult[i].split(",");
                var rssi = data[0];
                var distance = data[1];
                var rssisample = 8;
                    if(distance == 1){
                      //need to insert calculation method from php



                        temp.push(rssi);
                    }   

                }
            }

I have php file name myphpfile.php. So, I want to use variable and value from javascript to perform calculation in php file and return back to javascript. Please help me on this

This is my some part of php file. eg: myphpfile.php

    <?php

// $arrTimeRSSI will read from javascript before perform this calculation


//calculate mean X using array_sum() method
$avgRSSI = array_sum($arrTimeRSSI)/($num_of_elements); 

function StandardDeviation($arrTimeRSSI){
    global $num_of_elements;
    global $avgRSSI;

    $variance = 0.0;
   
    foreach($arrTimeRSSI as $x){
        //sum of squares of difference between all numbers and mean X
        $variance += pow(($x - $avgRSSI), 2);
       
    }
    $newElements = $num_of_elements - 1;
    return (float)sqrt($variance/$newElements); 

} ?>
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
Asma
  • 421
  • 1
  • 4
  • 6
  • 1
    You need to use ajax. There are tons of examples of this floating around. – GrumpyCrouton Oct 19 '20 at 12:43
  • 1
    you've already tagged this with AJAX, so we assume you know about AJAX, hopefully? If so, then what is your exact question / problem? This isn't a free write-my-code service, and it's not a tutorial site either. If you need an AJAX tutorial there are hundreds online already. We will help you with a **specific** programming question in your code, if you have one. What have you tried? Where are you stuck, exactly? – ADyson Oct 19 '20 at 12:53
  • is it need to use ajax type POST ? But my php file not contain method post. it still can be applied ? – Asma Oct 19 '20 at 12:53
  • "my php file not contain method post"...what does that mean? PHP can process POST requests easily, if you write code to make it do that. You should show us the PHP code for clarity, if you've already written it. Then we can see exactly what modifications would be needed, if any. – ADyson Oct 19 '20 at 14:14
  • i mean just a direct php script. i have update my question with my php file. Thank you very much for your advice. – Asma Oct 19 '20 at 14:42
  • Ok, thanks. So, precisely which values do you need to pass from the JavaScript? And how do they correspond to the variables in your PHP file? It's not quite clear - the names are not the same. Also, do you need to do the same calculation multiple times, for every row in your CSV? Or is it only one row? (Because, if there are many rows in the CSV which need processing, it would be more efficient to just upload the whole file to the server and process it there, and then return all the results back in one list.) – ADyson Oct 19 '20 at 15:15
  • 1. i need to pass value of rssi from javascript to php file. 2. the value of rssi in array, pass to variable $arrTimeRSSI in php to perform calculation. 3. I get your last point to upload at server side and return the result. But the javascript page have UI to upload (necessary to use) and show result. In my php just use to calculate, before this I manually import csv file and perform calculation. – Asma Oct 19 '20 at 15:42
  • Thanks. Regarding point 3, it's still not clear - do you need to process multiple rows from the CSV, or just one? It's fine to keep the UI which uploads the data, but that doesn't stop you changing the code where it interacts with the server. – ADyson Oct 19 '20 at 15:44
  • Thanks sir for helping me. yes, i need to process multiple rows from the CSV. Then how it will interact with server when I upload CSV in different page file? – Asma Oct 19 '20 at 15:56
  • Sorry I don't quite understand that question. We are concerned with _this_ page, surely, not a different page. Anyway https://stackoverflow.com/a/24939229/5947043 will help you know how to upload a file using jquery AJAX and PHP. From there, you can use https://stackoverflow.com/a/2805442/5947043 to know how to get the data from the CSV. Then you can pass each needed value into your StandardDeviation function, and get each result. I suggest storing all the results in a JSON array and returning that back to the Javascript. – ADyson Oct 19 '20 at 16:19

2 Answers2

1

It is not that simple because PHP is executed on the server and JavaScript by the client. You have to use ajax to send your request with data to a php script (to the server) and get the response back to the client.

This is an example how your JavaScript can look like:

$("#upload").on("click", function(){
    var csv = $('#csv');
    var csvFile = csv[0].files[0];
    var ext = csv.val().split(".").pop().toLowerCase();

    if($.inArray(ext, ["csv"]) === -1){
        alert('upload csv');
        return false;
    }
    if(csvFile != undefined){
        reader = new FileReader();
        reader.onload = function(e){

            csvResult = e.target.result.split(/\r|\n|\r\n/);
            
            var temp=[];
            for(i=0;i< csvResult.length; i++){
                if(csvResult[i] != "" && csvResult[i] != null){
                var data = csvResult[i].split(",");
                var rssi = data[0];
                var distance = data[1];
                var rssisample = 8;
                    if(distance == 1){
                        $.ajax({
                            url: '/path/to/phpfile.php',
                            type: 'post',

                            // transmit your data
                            data: {number1: '15', number2: '15'},

                            success: function (response) {
                                // handle the response
                                // response should contain 225 in this example
                            }
                        });
                        temp.push(rssi);
                    }   

                }
            }
        }
    }
});

And this is how your PHP file at /path/to/phpfile.php could look like:

// do your calculations here and echo it
echo intval($_POST['number1']) * intval($_POST['number2']);

Another method is to make a php file and embed your javascript in it. But this solution does not allow you to transfer data from javascript to php. Because the php function is executed on the server and the javascript (with the calculated part) is send to the client after that. Like this example:

<?php 

// declare your php function here
function calculate() {
    return;
}

?>

<script>
$("#upload").on("click", function(){
    var csv = $('#csv');
    var csvFile = csv[0].files[0];
    var ext = csv.val().split(".").pop().toLowerCase();

    if($.inArray(ext, ["csv"]) === -1){
        alert('upload csv');
        return false;
    }
    if(csvFile != undefined){
        reader = new FileReader();
        reader.onload = function(e){

            csvResult = e.target.result.split(/\r|\n|\r\n/);
            
            var temp=[];
            for(i=0;i< csvResult.length; i++){
                if(csvResult[i] != "" && csvResult[i] != null){
                var data = csvResult[i].split(",");
                var rssi = data[0];
                var distance = data[1];
                var rssisample = 8;
                    if(distance == 1){
                        var calculation = <?php echo calculate(); ?>
                        temp.push(rssi);
                    }
                }
            }
        }
    }
});
</script>
Robin Gillitzer
  • 1,603
  • 1
  • 6
  • 17
  • `processData: false, contentType: false` should not be necessary here as no file data is being sent, only two numbers. In fact using them might even cause problems. – ADyson Oct 19 '20 at 14:14
0

this can be done by creating a formdata and pass it to the php file which on it returns values. In my experience it is best to pass json values and return them from the php file as well. javascript function:

function example(){
  var form_data = new FormData();
  form_data.append("Variable1ToPass","test1");
  form_data.append("Variable2ToPass","test2");
  $.ajax({
    url: '/ThePhpFileYourReferTo.php',
    type: 'POST',
    dataType: 'json',
    cache: false,
    async: false,
    data: form_data,
    contentType: false,
    processData: false,
    error: function(ReturnData){
      //here do the error handling
      console.log(ReturnData);
      return;
    },
    success: function(ReturnData) {
      console.log(ReturnData.ResultOfCalculation);
      return;
    }
  });
}

In the php file (ThePhpFileYourReferTo.php):

$DataToReturn = [];
$DataToReturn['SubmittedValue'] = $_POST;
$Variable2ToPass = $_POST['Variable2ToPass'];
$Variable2ToPass = $_POST['Variable2ToPass'];
//here do the calculation and write in the return variable
$DataToReturn['ResultOfCalculation'] = "OK DONE";
header('Content-type: application/json');
echo json_encode($DataToReturn);
Dharman
  • 30,962
  • 25
  • 85
  • 135