garfee Posted August 14, 2013 Share Posted August 14, 2013 Hi there. Just a question I have at the moment, but will post my code if needed. I currently have an order form that I have been developing in php. However, it also uses javascript to calculate totals in real time, without the need to refresh the page. These totals are then passed to a html form and displayed. My goal is to pass these totals into a php mail function so they can be emailed once the html form submit button has been clicked. So my question is......... Is it possible to pass javascript variables to php ?? Code will follow if requested. Thanks in advance. Quote Link to comment Share on other sites More sharing options...
gristoi Posted August 14, 2013 Share Posted August 14, 2013 you have a few choices: 1. post all your data using ajax 2. add the value on the fly to a hidden field in your form so that it gets posted: <input type = "hidden" id="myValue" name = "myValue" /> //then in JS $('#myValue').val(// get the computed value); Quote Link to comment Share on other sites More sharing options...
Irate Posted August 14, 2013 Share Posted August 14, 2013 What gristoi said, you can generally pass your data via GET or POST requests (I do recommend using POST requests if the data is confidential - even if POST is only minimally more secure than GET in terms of detectability, GET requests pass the direct variables in the URL and are easily seen even by not-so-tech-savvy members). Example below. jQuery(document).ready(function(){ // lots of code and variable declarations omitted here... I will just assume you have yourvar and yourvalue declared already and that they are strings jQuery.ajax({ url: 'some/dir/some/path.php', data: yourvar + "=" + yourvalue }, function(data){ // do something with the result now console.log(data); // I decided to log it here, even though you would not want to do that in productive scripts }); }); Just a rough draft, that is, but it should do fine as long as you are using jQuery on your server/machine. Quote Link to comment Share on other sites More sharing options...
garfee Posted August 15, 2013 Author Share Posted August 15, 2013 Thanks for your help guys. I was wondering if I posted the code I have, if you could possibly let me know if I am on the right lines ? The Javascript that calculates the totals is below: // UTILITY FUNCTIONS function IsNumeric(n) { return !isNaN(n); } function CleanNumber(value) { // Assumes string input, removes all commas, dollar signs, and spaces newValue = value.replace(",",""); newValue = newValue.replace("£",""); newValue = newValue.replace(/ /g,''); return newValue; } function CommaFormatted(amount) { var delimiter = ","; var i = parseInt(amount); if(isNaN(i)) { return ''; } i = Math.abs(i); var minus = ''; if (i < 0) { minus = '-'; } var n = new String(i); var a = []; while(n.length > 3) { var nn = n.substr(n.length-3); a.unshift(nn); n = n.substr(0,n.length-3); } if (n.length > 0) { a.unshift(n); } n = a.join(delimiter); amount = "£" + minus + n; return amount; } // ORDER FORM UTILITY FUNCTIONS function applyName(klass, numPallets) { var toAdd = $("td." + klass).text(); var actualClass = $("td." + klass).attr("rel"); $("input." + actualClass).attr("value", numPallets + " pallets"); } function removeName(klass) { var actualClass = $("td." + klass).attr("rel"); $("input." + actualClass).attr("value", ""); } function calcTotalPallets() { var totalPallets = 0; $(".num-pallets-input").each(function() { var thisValue = $(this).val(); if ( (IsNumeric(thisValue)) && (thisValue != '') && (thisValue > 0)) { totalPallets += parseInt(thisValue); }; }); $("#total-pallets-input").val(totalPallets); } function calcProdSubTotal() { var prodSubTotal = 0; $(".row-total-input").each(function() { var valString = $(this).val() || 0; prodSubTotal += parseInt(valString); }); $("#product-subtotal").val(CommaFormatted(prodSubTotal)); } function calcShippingTotal() { var totalPallets = $("#total-pallets-input").val() || 0; var shippingRate = $("#shipping-rate").text() || 0; var shippingTotal = totalPallets * shippingRate; $("#shipping-subtotal").val(CommaFormatted(shippingTotal)); } function calcOrderTotal() { var orderTotal = 0; var productSubtotal = $("#product-subtotal").val() || 0; var shippingSubtotal = $("#shipping-subtotal").val() || 0; var underTotal = $("#under-box").val() || 0; var orderTotal = parseInt(CleanNumber(productSubtotal)) + parseInt(CleanNumber(shippingSubtotal)); $("#order-total").val(CommaFormatted(orderTotal)); $("#fc-price").attr("value", orderTotal); } // DOM READY $(function() { var inc = 1; $(".product-title").each(function() { $(this).addClass("prod-" + inc).attr("rel", "prod-" + inc); var prodTitle = $(this).text(); $("#foxycart-order-form").append("<input type='hidden' name='" + prodTitle + "' value='' class='prod-" + inc + "' />"); inc++; }); // Reset form on page load, optional $("#order-table input[type=text]:not('#product-subtotal')").val(""); $("#product-subtotal").val("£0"); $("#shipping-subtotal").val("£0"); $("#fc-price").val("£0"); $("#order-total").val("£0"); $("#total-pallets-input").val("0"); // "The Math" is performed pretty much whenever anything happens in the quanity inputs $('.num-pallets-input').bind("focus blur change keyup", function(){ // Caching the selector for efficiency var $el = $(this); // Grab the new quantity the user entered var numPallets = CleanNumber($el.val()); // Find the pricing var multiplier = $el .parent().parent() .find("td.price-per-pallet span") .text(); // If the quantity is empty, reset everything back to empty if ( (numPallets == '') ) { $el .removeClass("warning") .parent().parent() .find("td.row-total input") .val(""); var titleClass = $el.parent().parent().find("td.product-title").attr("rel"); removeName(titleClass); // If the quantity is valid, calculate the row total } else if ( (IsNumeric(numPallets)) && (numPallets != '') && (numPallets >= 0) ) { var rowTotal = numPallets * multiplier; $el .removeClass("warning") .parent().parent() .find("td.row-total input") .val(rowTotal); var titleClass = $el.parent().parent().find("td.product-title").attr("rel"); applyName(titleClass, numPallets); // If the quantity is invalid, let the user know with UI change } else { $el .addClass("warning") .parent().parent() .find("td.row-total input") .val(""); var titleClass = $el.parent().parent().find("td.product-title").attr("rel"); removeName(titleClass); }; // Calcuate the overal totals calcProdSubTotal(); calcTotalPallets(); calcShippingTotal(); calcOrderTotal(); }); }); The html table tht deals with the totals is below: <tr> <td colspan="6" style="text-align: right;">Product Subtotal: <input type="text" class="total-box" value="£0" id="product-subtotal" disabled="disabled"></td> </tr> </table> <div id="totals"> <!-- <div class="clear"></div>--> <!-- <div style="text-align: right;">--> <span>ORDER TOTAL: </span> <input type="text" class="total-box" value="£0" id="order-total" disabled="disabled"></div> <br /> <form class="mailOrder" action="mail_order.php" method="post" accept-charset="utf-8" id="mail-order-form"> <input type="hidden" name="name" value="Multi Product Order" /> <input type="hidden" id="fc-price" name="price" value="0" /> <input type="submit" value="Submit Order" class="submit" /> </form> </div> <div id="shiptable"> <table id="shipping-table"> <tr> <!-- <th>Total Qty.</th>--> <th>Shipping Rate</th> <th style="text-align: right;">Shipping Total</th> </tr> <tr> <!-- <td id="total-pallets"><input id="total-pallets-input" value="0" type="text" disabled="disabled"></td>--> <td id="shipping-rate">0.00</td> <td style="text-align: right;"><input type="text" class="total-box" value="£0" id="shipping-subtotal" disabled="disabled"></td> </tr> </table></div> And of course the php: <?php // This function checks for email injection. Specifically, it checks for carriage returns - typically used by spammers to inject a CC list. function isInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; if(preg_match($inject,$str)) { return true; } else { return false; } } // Load form field data into variables. $order_total = $_REQUEST['order-total'] ; $product_subtotal = $_REQUEST['product-subtotal'] ; // If the user tries to access this script directly, redirect them to feedback form, if (!isset($_REQUEST['order-total'])) { header( "Location: feedback_form.php" ); } // If the form fields are empty, redirect to the error page. elseif (empty($order_total) || empty($product_subtotal)) { header( "Location: error_message.php" ); } // If email injection is detected, redirect to the error page. elseif ( isInjected($email_address) ) { header( "Location: error_message.html" ); } // If we passed all previous tests, send the email! else { mail( "name@example.com", "Feedback Form Results", $order_total, "From: $email_address" ); header( "Location: thank_you.php" ); } ?> Any further pointers on this would be greatly appreciated. I am still learning as I go. Thanks in advance. Quote Link to comment Share on other sites More sharing options...
gristoi Posted August 15, 2013 Share Posted August 15, 2013 looks good, always try to keep the JS / css / html and php seperated wherever possible. Makes the code easier to follow. one thing i would advise to do is to replace : $_REQUEST with $_POST or $_GET. You will know when creating the form how you are sending the data across ( post / get etc ) Quote Link to comment Share on other sites More sharing options...
garfee Posted August 15, 2013 Author Share Posted August 15, 2013 (edited) Hi gristoi. On submit, it takes me to the feedback_form.php. So it is thinking I am trying to access the script directly. Can you think of anything obvious I am missing ? Racking my brains but cannot think why it would be doing this. ***************Update********************* Having removed the if statement that redirects to feedback_form.php, on submit it redirects to the error_message.php page. So it is assuming the fields are empty. Not sure if it is relevant but I am using XXAMP testing server. Edited August 15, 2013 by garfee Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.