Search code examples
javascriptphppostsum

Change PHP code to JS


Hello I have a code in PHP that catches some values inserted in other page and it adds all values and in the next page it shows the "total" and I want to know if is it possible to make the same function of this code in JavaScript.

<?php

  $ak1 = $_POST['ak1'];
  $ak2 = $_POST['ak2'];
  $ak3 = $_POST['ak3'];
  $ak4 = $_POST['ak4'];
  $ak5 = $_POST['ak5'];
  $ak6 = $_POST['ak6'];
  $ak7 = $_POST['ak7'];

  //CS AK

  $akcs1 = $_POST['akcs1'];
  $akcs2 = $_POST['akcs2'];
  $akcs3 = $_POST['akcs3'];
  $akcs4 = $_POST['akcs4'];
  $akcs5 = $_POST['akcs5'];
  $akcs6 = $_POST['akcs6'];
  $akcs7 = $_POST['akcs7'];

?>
<?php


echo '<p><i>Sent at:</i>';
echo date('H:i, jS F');

$total = 0;

$total = $ak1 + $ak2 + $ak3 + $ak4 + $ak5 + $ak6 + $ak7 + $akcs1 + $akcs2 + $akcs3 + $akcs4 + $akcs5 + $akcs6 + $akcs7;

echo '<br><br><br><strong>Total: </strong>'.$total;

echo '<hr width="20%">';

if( $total == 0)
{
  echo '<br><br><strong>You did not make any order</strong>';
}

$value = 0.00;

define('ak1p', 140);
define('ak3p', 160);
define('ak4p', 120);
define('ak5p', 180);
define('ak6p', 210);
define('ak7p', 250);
define('ak2p', 285);

define('ak1csp', 120);
define('ak3csp', 200);
define('ak4csp', 110);
define('ak5csp', 110);
define('ak6csp', 130);
define('ak7csp', 200);
define('ak2csp', 300);

$value =      $ak1 * ak1p
            + $ak3 * ak3p
            + $ak4 * ak4p
            + $ak5 * ak5p
            + $ak6 * ak6p
            + $ak7 * ak7p
            + $ak2 * ak2p
            + $akcs1 * ak1csp
            + $akcs3 * ak3csp
            + $akcs4 * ak4csp
            + $akcs5 * ak5csp
            + $akcs6 * ak6csp
            + $akcs7 * ak7csp
            + $akcs2 * ak2csp;

echo '<strong>Total to pay: </strong><font face color="green">'.$value.'</font><strong> $</strong>'; 


?>

Solution

  • However, let's look at the code you posted.

    I think it would help to refactor this code into a more logical sense before attempting this in Javascript. That should make it easier to transpose. Every time there is repetition of similar code (e.g. $ak1 = $_POST['ak1']; $ak2 = $_POST['ak2']; ... ) I would think there must be a more efficient way of getting your programming language to do the hard work. Computers are good at repetitive tasks after all.

    I assume you have labelled all of the input fields in your form individually but you can actually pass them to $_POST as arrays if you give them all the same name and append square brackets like so:

    <input type="text" name="ak[]">
    <input type="text" name="ak[]">
    <input type="text" name="ak[]">
    <input type="text" name="ak[]">
    <input type="text" name="ak[]">
    <input type="text" name="ak[]">
    <input type="text" name="ak[]">
    
    <input type="text" name="akcs[]">
    <input type="text" name="akcs[]">
    <input type="text" name="akcs[]">
    <input type="text" name="akcs[]">
    <input type="text" name="akcs[]">
    <input type="text" name="akcs[]">
    <input type="text" name="akcs[]">
    

    I don't know why you have two different sets of names for the input fields - it might help to merge these into one unless you have a good reason not too.

    Now you have the HTML in a more maintainable format, you can seriously cut down on the amount of variable assignment that is needed in PHP:

    if(isset($_POST['ak'], $_POST['akcs'])){
      extract($_POST);
      $all_fields = array_merge($ak, $akcs);
      $total = array_sum($all_fields);
      if($total){
        echo "<p><i>Sent at:</i>" . date('H:i, jS F');
        $ak_values   = [140, 285, 160, 120, 180, 210, 250, 120, 300, 200, 110, 110, 130, 200];
        $value = array_sum(array_map(function($a, $b){
          return $a * $b;
      }, $all_fields, $ak_values));
        echo '<br><br><br><strong>Total: </strong>'.$total;
        echo '<hr width="20%">';
        echo '<strong>Total to pay: </strong><font face color="green">'.$value.'</font><strong> $</strong>';
      } else {
      echo '<br><br><strong>You did not make any order</strong>';
      }
    }
    

    Making use of PHP's features such as extract, array_sum, array_map and array_merge (which is necessary to combine the two sets of input fields in your form - see? You know it makes sense to only have the one type ;) ) makes it much less repetitive and also more maintainable should you wish to amend the form at a later date.

    So how does this convert to JavaScript?

    I'm glad you asked.

    var ak_values   = [140, 285, 160, 120, 180, 210, 250, 120, 300, 200, 110, 110, 130, 200];
    var order_date = document.getElementById('order_date');
    var message = document.getElementById('message');
    function sum(a,b){ return a+b }
    document.getElementById('sum').addEventListener('click', function(){
      var ak = [];
      Array.prototype.slice.call(document.querySelectorAll('[name="ak[]"], [name="akcs[]"]')).forEach(function(i){
        ak.push( i.value === "" ? 0 : parseInt(i.value));
    });
      var total = ak.reduce(sum);
      if (total){
        order_date.innerHTML =  "<i>Sent at:</i>" + new Date();
        ak = ak.map(function(item, index){
          return item * ak_values[index];
        });
        var value = ak.reduce(function(sum, item){
          return sum + item;
        });
        message.innerHTML = '<br><br><br><strong>Total: </strong>' + total + '<hr width="20%"><strong>Total to pay: </strong><font face color="green">' + value  + '</font><strong> $</strong>';
      } else{
        message.innerHTML = '<br><br><strong>You did not make any order</strong>';
      }
    });
    

    Javascript has comparable functions for map and reduce to get the array sum etc. and you can see how taking the approach in PHP to use such standard functions makes it easier to translate in to another language.

    A few things to consider:

    • Do you want these sorts of calculations to occur in the browser? The prices presumably would be stored in a database which would need to be retrieved
    • The user can manipulate values (like the ones stored in the var ak_values array) in Javascript
    • Using AJAX might be better?
    • Inline styles?

    Here is a (slightly ugly) but working JSFiddle https://jsfiddle.net/codebubb/3tht5y8v/1/