0

I have a simple calculation from php database, which needs to be used in javascript, how to do it?

    <script>
    function check(){
    var ramt=document.getElementByName('refundedamount[]');
    var bal1=[];
    <?php for each($balance1 as $val){
    echo 'bal1.push('.$val.');';
    } ?>
    . . .  
    } </script>

    <form onsubmit="return check()";
    <?php
    $balance1=array();
    while($row=mysqli_fetch_assoc($result)){
    $income=$row['totalincome'];
    $exp=$row['totalexp'];
    $balance=$income-$exp;
    $balance1[]=$balance;
    ...... ?>
   <input type="text" name="refundedamount[]"/>
   </form>

How to use and read values of $balance1[] array into JAVASCRIPT. without using JSON. basically I want to cross check the value of php $balance1 array and input text array " refundedamount[]".

haju
  • 21
  • 5
  • You may consider to convert the php array into JSON format. – The KNVB Dec 12 '17 at 09:41
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) –  Dec 12 '17 at 09:44
  • I didnt know that you dont want to use JSON. I updated my answer below – Eddie Dec 12 '17 at 10:07

3 Answers3

0

Without JSON, you can loop each value.

<?php 
    $balance1 = array( 1,2,3,4,5 );
?>

<script>
    var balance1 = [];
    <?php
    foreach( $balance1 as $val ) {
        echo 'balance1.push( ' . $val .  ' );';
    }
   ?>
   console.log( balance1 );
</script>

Will result to

Array [ 1, 2, 3, 4, 5 ]
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

PHP side:

$arrayJSON = json_encode($balance1) to convert to JSON format.

JS side:

var array = JSON.parse("<?php echo $arrayJSON;?>");

Hope this help!

Cuong Vu
  • 3,423
  • 14
  • 16
0

You can convert the php array into a javascript object then convert that object into an array, eg if it has numeric indices:

<script>

var obj = <?php echo json_encode($phpArray) ?>;
var arr = Object.keys(obj).map(function(k) { return obj[k] });

// Or if you're using ES6
var arr = Object.values(obj);

</script>
omarjebari
  • 4,861
  • 3
  • 34
  • 32