#1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    524
    Rep Power
    50

    Passing an array to Javascript


    Hi:

    I have an order form which uses javascript to calculates lim-item totals and order totals when a user enters a quantity. The price can be either a "standard" price or a "member" price depending on the user's membership status. The price data comes from a table where each record includes a "product_id", "standard_price" and "member_price". This system works really well. (see "original_code" below)

    Now, I would like to offer "tiered pricing" where the unit price is not fixed but is dependent on how many units the user purchased. There is a "price threshold" table which where every record includes "product_id", "price_threshold", "standard_price", and "member_price".There are multiple records per product depending on how many "tiers" that product has. If a user enters a quantity, the system should look up that quantity by "product_id" and "price_threshold", that matches the quantity and use that unit price to calculate subtotal.

    The problem is, I am not sure how to pass the threshold array to Javascript to lookup the correct threshold.

    The existing code looks like this:

    Customer entry form (line for each product)
    PHP Code:
          echo <<<EOT
              <TR>  
                <TD align="right">  
                  
    $product_name
                </TD>  
                <TD>   
                  <INPUT type="text" name="ttl_units[
    $i]" class="unitCount" data-id="$i" data-standard="$standard_price" data-member="$member_price" size="8" maxlength="6" value="0" /> 
                  <INPUT type="hidden" name="prod_id[
    $i]" value="$product_id" /> 
                  <INPUT type="hidden" name="prod_name[
    $i]" value="$product_name" /> 
                  <INPUT type="hidden" name="price_type_label[
    $i]" value="$price_type_label" /> 
                  <INPUT type="hidden" name="unit_price[
    $i]" id="unit_price[$i]" value="0" /> 
                  <INPUT type="hidden" name="subttl[
    $i]" class="subVal" id="subttl[$i]" value="0" /> 
                  (
    $price_type_label)
                </TD>  
                <TD>   
                  <SPAN id="unitPriceDisp
    $i"> $0 </SPAN> 
                </TD>  
                <TD>   
                  $<INPUT type="text" name="subttl[
    $i]" id="unitSubDisp$i"  size="8" maxlength="6" value="0" /> 
                </TD> 
              </TR>  
    EOT; 
    Javascript that does the math:
    PHP Code:
    echo <<<EOT
        <script type="text/javascript">  
          $('.unitCount').keyup(function(e){ 
            var unitCount = $(this).val(); 
            var unitSubId = $(this).attr('data-id'); 
            var unitPrice = {'standard': +$(this).attr('data-standard'), 'member': +$(this).attr('data-member'), 'joining': +$(this).attr('data-member')};  
            var memType = document.getElementById("memSelect").value; 
            var memFee = 19.99; //document.getElementById("level").value * 100; 
            var grandTotal = 0.00; 
            var unitSub = (unitCount * unitPrice[memType]);
            document.getElementById('unitPriceDisp'+unitSubId).innerHTML = '$'+unitPrice[memType].toFixed(2); 
            document.getElementById('unitSubDisp'+unitSubId).value = unitSub.toFixed(2); 
            document.getElementById('unit_price['+unitSubId+']').value = unitPrice[memType].toFixed(2); 
            document.getElementById('subttl['+unitSubId+']').value = unitSub.toFixed(2); 
            $('.subVal').each(function() { grandTotal += +this.value }); 
            if(memType == "joining") {
              grandTotal += memFee; 
              document.getElementById('MembershipFee').innerHTML = '$'+memFee.toFixed(2);
            }
            document.getElementById('GrandTotal').innerHTML = '$'+grandTotal.toFixed(2); 
          }); 
        </script> 
    EOT; 
    The PHP code which extracts the "Price Thresholds" looks like the following:
    PHP Code:
    $num_price_thresholds 10;
    $price_th_count= array(); 
    $price_th_id = array(); 
    $price_th_value = array(); 
    $pt_standard_price = array(); 
    $pt_member_price = array(); 
    // Get Badge Thresholds for this Product

    $get_thresholds "SELECT * FROM product_price_thresholds
                        WHERE product_id = 
    $product_id";        
    $thresholds_result mysql_query($get_thresholds$conn) or die(mysql_error());
    $i=0;
    while (
    $thresholdsArray mysql_fetch_array($thresholds_result)) {
        
    $price_th_count $i;
        
    $product_threshold_id  $thresholdsArray['product_threshold_id'];
        
    $price_threshold_value  $thresholdsArray['price_threshold_value'];
        
    $pt_standard_price  $thresholdsArray['pt_standard_price'];
        
    $pt_member_price  $thresholdsArray['pt_member_price']; 
    I'm struggling to see how to use the "threshold" arrays in the javascript calculations.

    Any suggestions would be greatly appreciated.

    Thanks!
  2. #2
  3. Forgotten Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,105
    Rep Power
    9644
    It's hard to tell: do you have the Javascript at a point where you can hardcode some array or whatever with the values and it works? And you just need to get the array/whatever from PHP into the Javascript?
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    524
    Rep Power
    50
    No... I guess it's a two stage problem?
    1. How do I pass the php array to javascript?
    2. How do I parse it / use it in javascript?

    Thanks for your reply.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,281
    Rep Power
    629
    Is this what you are looking for:
    PHP Code:
    <script type='text/javascript'>
        <?php
        $php_array 
    = array('abc','def','ghi');
        
    ?>
        var js_array = [<?php echo '"'.implode('","'$php_array).'"' ?>];
        alert(js_array[0]);
    </script>
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    524
    Rep Power
    50
    Thanks.

    I will noodle this for a while and see what I come up with... I am sure there will be more questions, LOL.
  10. #6
  11. Forgotten Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,105
    Rep Power
    9644
    I'd suggest json_encode instead:
    PHP Code:
    <script type='text/javascript'>
        <?php
        $php_array 
    = array('abc','def','ghi');
        
    ?>
        var js_array = <?php echo json_encode($php_array); ?>;
        alert(js_array[0]);
    </script>
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    524
    Rep Power
    50
    Sorry not to follow up sooner, I had to put this aside for a while...

    So, as a test, what I have is:
    PHP Code:
    <!DOCTYPE html>
    <html>
    <body>

    <?php
        
        $test_array 
    = array('abc','def','ghi');
      
        
    $price_array = array();
        
    $price_array[] = array('product_id' => '260''qty' =>'1''price' => '100');
        
    $price_array[] = array('product_id' => '260''qty' =>'3''price' => '75');
        
    $price_array[] = array('product_id' => '263''qty' =>'1''price' => '200');
        
    $price_array[] = array('product_id' => '264''qty' =>'1''price' => '225');

        foreach(
    $price_array as $row) {
              echo 
    'Buy '$row['qty'], ' of product '$row['product_id'], ' for $'$row['price'], ' each. '"<br>";
        }
    ?>

    <script type='text/javascript'>
        var cat = 32;
        alert (cat);
        var js_array = <?php echo json_encode($test_array); ?>;
         alert(js_array[0]);
       
        var price_array = <?php echo json_encode($price_array); ?>;
        alert(price_array[0][0]);   
    </script>
    </body>
    </html>
    This works fine, where I am referencing the non-associative array, $test_array.

    The problem is with the associative array, $price_array. How do I extract the values from the associative array so I can use them in a javascript routine.

    Thanks
    Last edited by SeanF; April 30th, 2017 at 10:24 AM.
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    524
    Rep Power
    50
    Ah!. I need to call the second array by field name :
    PHP Code:
        alert(price_array[1]['product_id']); 
    That should get me a little further....

    Comments welcome.
  16. #9
  17. Forgotten Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,105
    Rep Power
    9644
    I know you have your answer already, but
    Originally Posted by SeanF
    How do I extract the values from the associative array so I can use them in a javascript routine.
    It works the same way that it would in PHP.
    PHP Code:
    echo $price_array[0]["product_id"]; 
    Code:
    alert(price_array[0]["product_id"]);
    With objects* it's generally better to use object syntax instead of array syntax. I don't know a real reason for it but I'm sure there is one.
    Javascript treats associative arrays and objects the same way, unlike PHP, so
    PHP Code:
    // echo $price_array[0]->product_id; // does not work 
    Code:
    alert(price_array[0].product_id); // works

    * Javascript does not have associative arrays. It has objects. Objects can be accessed using [] array syntax, which is sometimes handy, but they are still objects.
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    524
    Rep Power
    50
    OK... so trying to put the pieces together, I am trying to search for a price for a specific product_id where quantity is a certain value.

    What I have so far is:

    PHP Code:
    <!DOCTYPE html>
    <html>
    <body>

    <?php
        $test_array 
    = array('abc','def','ghi');
      
        
    $price_array = array();
        
    $price_array[] = array('product_id' => '260''qty' =>'1''price' => '100');
        
    $price_array[] = array('product_id' => '260''qty' =>'3''price' => '75');
        
    $price_array[] = array('product_id' => '263''qty' =>'1''price' => '200');
        
    $price_array[] = array('product_id' => '264''qty' =>'1''price' => '225');

        foreach(
    $price_array as $row) {
              echo 
    'Buy '$row['qty'], ' of product '$row['product_id'], ' for $'$row['price'], ' each. '"<br>";
        }
        
        echo 
    "
        Enter a number: <input type=\"text\" id=\"quantity\">
        $<INPUT type=\"text\" name=\"subttl\" id=\"unitSubDisp\"  size=\"10\" maxlength=\"10\" value=\"0\" /> 
         <p id=\"priceList\"></p>
         <p id=\"demoQTY\"></p>"
    ;
    ?>

    <script type='text/javascript'>
        var price_array = <?php echo json_encode($price_array); ?>;   
        // alert(price_array[0]['product_id']);  // array
        // alert(price_array[1].product_id); // object  
        var text = "";
        var i;
        for (i = 0; i < price_array.length; i++) {
            if(price_array[i].product_id == 260){
                text += price_array[i].product_id + "<br>";
                document.getElementById("priceList").innerHTML = text;   
                // var qty = 2;
                function getPrice(qy) {
                    return qy >= 1;
            }
                document.getElementById("demoQTY").innerHTML = price_array[i].qty.find(getPrice);
    }
        }
    </script>
    </body>
    </html>
    The scripts seem to be able to get the array values but my syntax for either the "return" function or the "document.getElementById" is causing an error. I've tried a million different things but I think I'm barking up the wrong tree.

    Any comments would be appreciated.

    Thanks
  20. #11
  21. Super Moderator
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Location
    London, UK
    Posts
    4,004
    Rep Power
    2793
    This syntax is wrong.
    Javascript Code:
    document.getElementById("demoQTY").innerHTML = price_array[i].qty.find(getPrice);

    I think you intended this
    Javascript Code:
    document.getElementById("demoQTY").innerHTML = getPrice(price_array[i].qty);

    Why not just use this?
    Javascript Code:
    price_array[i].product_id == 260 && price_array[i].qty == 1

    If you want to use find. Check out this reference.
    Last edited by Winters; June 16th, 2017 at 01:19 PM. Reason: Additional
    [PHP] | [Perl] | [Python] | [Java] != [JavaScript] | [XML] | [C] | [C++] | [LUA] | [MySQL] | [FirebirdSQL] | [PostgreSQL] | [HTML] | [XHTML] | [CSS]
  22. #12
  23. Super Moderator
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Location
    London, UK
    Posts
    4,004
    Rep Power
    2793
    Just saw the date. I am such a necro poster..
    [PHP] | [Perl] | [Python] | [Java] != [JavaScript] | [XML] | [C] | [C++] | [LUA] | [MySQL] | [FirebirdSQL] | [PostgreSQL] | [HTML] | [XHTML] | [CSS]

IMN logo majestic logo threadwatch logo seochat tools logo