Jump to content

Pass value from jquery to php on same page instantly

For an extra credit project in m web design class, we have been instructed to use jquery and php to have the price of an item, which is displayed already on the page, update instantly with a new price depending on what form of shipping the user selects from an HTML form on the same page. I have very limited experience with Jquery, and would like to know how I would go about dynamically updating the price in this way. The webpage code, which is taking data from a previous form page, is below. Any and all assistance is greatly appreciated!

 

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Order</title>
<link rel="icon" href="/student/webdesign/2015/4th/04_26/favicon.ico">
<?php

    $qty = $_POST["qty"];
    $size = $_POST["size"];
    $shape = $_POST["shape"];
    $total = $qty*$size;
    $tax = $total*0.0775;
    $priceWithTax = $tax + $total;
    

?>
</head>

<body>
<h3>Your Order</h3>
    <p>
        You have ordered <strong><?php echo $qty; ?></strong> <strong><?php if ($size == "5.99") { echo "small";    } elseif ($size == "7.99") {echo "medium";} else {echo "large";} ?></strong> sized <strong><?php echo $shape; ?></strong>     <?php if ($qty == 1) {echo "pizza";} else {echo "pizzas";} ?>.
        <br>
        Your price before tax is <?php echo "". money_format('$%i', $total) .".";  ?>
        <br>
        Your price including tax, is <?php echo "". money_format('$%i', $priceWithTax) ."."; ?>
        <br>
        With shipping, your price comes out to <!-- Dynamic Price: $priceWithTax + shipping -->
    </p>
<h3>Shipping and Billing Information</h3>
    <form action="/student/webdesign/2015/4th/04_26/classwork/checkout/verify3.php" method="post" name="form" id="form">
      <p>
        <label for="shipping">Shipping:</label>
        <select name="shipping" id="shipping">
          <option>Choose One</option>
          <option value="4.99">15 Min. - $4.99</option>
          <option value="3.99">25 Min. - $3.99</option>
          <option value="1.99">45 min - $1.99</option>
          <option value="0">1 hour - Free</option>
        </select>
      </p>
      <p>
        <label for="fname">First Name:</label>
        <input type="text" name="fname" id="fname">
        <label for="lname">Last Name:</label>
        <input type="text" name="lname" id="lname">
      </p>
      <p>
        <label for="email">E-Mail:</label>
        <input type="text" name="email" id="email">
        <label for="phone">Phone Number:</label>
        <input type="text" name="phone" id="phone">
      </p>
      <p>
        <label for="address">Street Address:</label>
        <input type="text" name="address" id="address">
      </p>
      <p>
        <label for="city">City:</label>
        <input type="text" name="city" id="city">
      </p>
      <p>
        <label for="state">State:</label>
        <select name="state" id="state">
        <option>Choose One</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District Of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NV">Nevada</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
        </select>
      </p>
      <p>
        <label for="zip">Zip:</label>
        <input type="text" name="zip" id="zip">
      </p>
      <p>
        <label for="cardType">Credit Card Type:</label>
        <select name="cardType" id="cardType">
          <option value="visa">Visa</option>
          <option value="mastercard">MasterCard</option>
          <option value="discover">Discover</option>
          <option value="amex">American Express</option>
        
        </select>
      </p>
      <p>
        <label for="cardNum">Credit Card Number:</label>
        <input type="text" name="cardNum" id="cardNum">
      </p>
      <p>
        <label for="cardCode">Security Code:</label>
        <input type="text" name="cardCode" id="cardCode">
      </p>
          <p>Expiration Date: 
            <label for="cardMonth">Month:</label>
            <select name="cardMonth" id="cardMonth">
              <option value="01">01</option>
              <option value="02">02</option>
              <option value="03">03</option>
              <option value="04">04</option>
              <option value="05">05</option>
              <option value="06">06</option>
              <option value="07">07</option>
              <option value="08">08</option>
              <option value="09">09</option>
              <option value="10">10</option>
              <option value="11">11</option>
              <option value="12">12</option>
            </select>
            <label for="cardYear">Year:</label>
            <select name="cardYear" id="cardYear">
            <option>Choose Year</option>
          <?php
        for ($i=2016; $i<=2020; $i++) {
        echo "<option value=".$i.">".$i."</option>";     
        }
        ?>
            </select>
          </p>
      <p>
     <input type="submit">
     </p>
        <input name="qty" type="hidden" id="qty" value="<?php echo $qty ?>">
        <input name="size" type="hidden" id="size" value="<?php echo $size ?>">
        <input name="shape" type="hidden" id="shape" value="<?php echo $shape ?>">
        <input name="total" type="hidden" id="total" value="<?php echo $total ?>">
        <input name="priceWithTax" type="hidden" id="priceWithTax" value="<?php echo $priceWithTax ?>">
      </p>
      <p>&nbsp;</p>
</form>
    <p>&nbsp;</p>
    

</body>
</html>

Link to comment
Share on other sites

Link to post
Share on other sites

jquery = javascript

javascript runs in the browser (client side), the php is server side.

 

TL;DR: it's not possible to pass a variable from jquery to php

 

but you can adjust values with jquery :)

$('#price').text(price);

^ sets the element with the "price" id to the value of the "price" variable :)

Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, mikat said:

jquery = javascript

javascript runs in the browser (client side), the php is server side.

 

TL;DR: it's not possible to pass a variable from jquery to php

 

but you can adjust values with jquery :)


$('#price').text(price);

^ sets the element with the "price" id to the value of the "price" variable :)

it is possible...

 

if you can inject the php client side instead of having it go active on the server side then it is possible. just run a code pass through and initiate it on the client side, the client creates a proxy server where you can inject veriables... then send a passthrough back to server side with whatever you need...

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, canadiansteve2 said:

it is possible...

 

if you can inject the php client side instead of having it go active on the server side then it is possible. just run a code pass through and initiate it on the client side, the client creates a proxy server where you can inject veriables... then send a passthrough back to server side with whatever you need...

yes, but you're refreshing the entire page, not really ideal :)

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, mikat said:

yes, but you're refreshing the entire page, not really ideal :)

what do you mean why would it need to refresh???

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, mikat said:

TL;DR: it's not possible to pass a variable from jquery to php

That's incorrect.

 

What you are looking to do is use an Ajax call. Using jQuery or pure JS if you wanted to you can get the form data and submit it to a PHP script in the background.

 

The PHP script can then calculate the price and return this data which JS can then display on the webpage all without refreshing the page

Link to comment
Share on other sites

Link to post
Share on other sites

It wasn't that long ago when I was able to wake up, check out the forums I followed and not have to reply becuase the answers were always perfect.

 

You want to run a function when a user clicks on one of the shipping options. You have 2 options for triggers. onChange() and onInput(). They both do almost the same thing, but for the function to run with onChange(), the user has to click off of the <select>, meaning that it won't happen instantly as you wanted.

 

First, you need to alter your HTML code slightly. You need to wrap this line in a span tag like so

With shipping, your price comes out to <!-- Dynamic Price: $priceWithTax + shipping -->

<span id="dynamicTotal">With shipping, your price comes out to <!-- Dynamic Price: $priceWithTax + shipping --></span>

Doing this will allow us to target this element with Jquery on completion of the call.

 

As for getting server side interaction, I would honestly prefer to use straight javascript for everything but the actual AJAX call, however, you seem to want more weight on Jquery. To do this we're going to add an 'event listener' which will detect whether or not the onInput() tigger has occured.

$( "#shipping" ).on( "input", function() {
  //make the AJAX call
});

If you're not super familiar with Jquery I will explain a little, otherwise skip to the next code block. The first item in the brackets is the <select> for shipping, then we attach an 'on' event to it. Similar to plain javascript, where you have onChange, onSubmit, onLoad etc. the 'on' event does the same thing, you just specify which event later. Which is the next part in brackets, you can specify which event as the first variable. The function is what runs after the 'input' has been triggered.

 

Next, we need to actually make the AJAX call, thankfully Jquery makes it extremely easy

$.ajax({
	url: 'resolvePrice.php',
	type: 'GET',
	data: data,
	success: function(data){
		$('#dynamicTotal').html(data);	
		}
})

Note that we still need to tell javascript what actually gets sent to PHP. Right now, we have data: data, which is telling it to send the data variable.... Which doesn't exist. We need to create that. We need to send 2 variables, the current total, plus the shipping option. Luckily, your code already supports both of these things. We just need to format it for PHP, so, like a query string.

We can do this like so

var currentTotal = $('#priceWithTax').value();
var option = $('#shipping').value();
var data = 'currentTotal=' + currentTotal + '&option=' + option

That's the parts to the Jquery function, so together it is

$( "#shipping" ).on( "input", function() {
	var currentTotal = $('#priceWithTax').value();
	var option = $('#shipping').value();
	var data = 'currentTotal=' + currentTotal + '&option=' + option;
    $.ajax({
        url: 'resolvePrice.php',
        type: 'GET',
        data: data,
        success: function(data){
            $('#dynamicTotal').html(data);	
            }
    });
});

This code goes between a <script></script> tag in your HTML.

 

Finally, we need to make the PHP page to handle what you're sending it. I named it resolvePrice.php, but it can be whatever. In it, you need to have something similar to this

<?php 
$possibe_results = array("4.99", "3.99", "1.99", "0");
if(!in_array($_GET['option'], $possibe_results)){
	exit();
}else{
	$shipping = $_GET['option'];
}
$currentTotal = $_GET['currentTotal'];
$newTotal = $currentTotal + $shipping;
echo htmlspecialchars('With shipping, your price comes out to <!-- Dynamic Price: ' . $newTotal . ' + shipping -->');
?>

As you only have set possible options, this code checks against this, and if the query doesn't match one of the possible results, it's likely that something malicious is going on, so the script just exits. Otherwise, it's all relatively straight forward...... Aaaaaaaaaaaaaaaand, sorry for the long post

I am good at computer

Spoiler

Motherboard: Gigabyte G1 sniper 3 | CPU: Intel 3770k @5.1Ghz | RAM: 32Gb G.Skill Ripjaws X @1600Mhz | Graphics card: EVGA 980 Ti SC | HDD: Seagate barracuda 3298534883327.74B + Samsung OEM 5400rpm drive + Seatgate barracude 2TB | PSU: Cougar CMX 1200w | CPU cooler: Custom loop

Link to comment
Share on other sites

Link to post
Share on other sites

Thanks to everyone who put in advice. Hazy125, I won't be able to test the code until tomorrow in class, but I really appreciate you taking the time to explain everything, and I understand at least at a basic level how your solution works. I will keep this thread updated with my progress. Thanks so much!

Link to comment
Share on other sites

Link to post
Share on other sites

No problem, one thing to note, you said you were using Jquery, but I don't see you including a Jquery file anywhere in your code. You will need to include the Jquery script for anything I said to work

I am good at computer

Spoiler

Motherboard: Gigabyte G1 sniper 3 | CPU: Intel 3770k @5.1Ghz | RAM: 32Gb G.Skill Ripjaws X @1600Mhz | Graphics card: EVGA 980 Ti SC | HDD: Seagate barracuda 3298534883327.74B + Samsung OEM 5400rpm drive + Seatgate barracude 2TB | PSU: Cougar CMX 1200w | CPU cooler: Custom loop

Link to comment
Share on other sites

Link to post
Share on other sites

Hazy125-

 

I have added these elements to my original page: 

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Order</title>
<link rel="icon" href="/student/webdesign/2015/4th/04_26/favicon.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
$( "#shipping" ).on( "input", function() {
    var currentTotal = $('#priceWithTax').value();
    var option = $('#shipping').value();
    var data = 'currentTotal=' + currentTotal + '&option=' + option;
    $.ajax({
        url: 'http://foothillertech.com/student/webdesign/2015/4th/04_26/classwork/checkout/assets/resolvePrice.php',
        type: 'GET',
        data: data,
        success: function(data){
            $('#dynamicTotal').html(data);    
            }
    });
});
</script>
<?php
    $qty = $_POST["qty"];
    $size = $_POST["size"];
    $shape = $_POST["shape"];
    $total = $qty*$size;
    $tax = $total*0.0775;
    $priceWithTax = $tax + $total;
    
?>
</head>
<body>
<h3>Your Order</h3>
    <p>
        You have ordered <strong><?php echo $qty; ?></strong> <strong><?php if ($size == "5.99") { echo "small";    } elseif ($size == "7.99") {echo "medium";} else {echo "large";} ?></strong> sized <strong><?php echo $shape; ?></strong>     <?php if ($qty == 1) {echo "pizza";} else {echo "pizzas";} ?>.
        <br>
        Your price before tax is <?php echo "". money_format('$%i', $total) .".";  ?>
        <br>
        Your price including tax, is <?php echo "". money_format('$%i', $priceWithTax) ."."; ?>
        <br>
        <span id="dynamicTotal">With shipping, your price comes out to  </span>
    </p>

 

In addition, I created a resolvePrice.php file and put the following code into it: 

<?php 
$possibe_results = array("4.99", "3.99", "1.99", "0");
if(!in_array($_GET['option'], $possibe_results)){
	exit();
}else{
	$shipping = $_GET['option'];
}
$currentTotal = $_GET['currentTotal'];
$newTotal = $currentTotal + $shipping;
echo htmlspecialchars('With shipping, your price comes out to ' . $newTotal . ');
?>

However, the price did not update dynamically with different choices of shipping options. Here is a link to the first in the series of pages which our current project is based on, the second of which consists of the code in my original post: http://foothillertech.com/student/webdesign/2015/4th/04_26/classwork/checkout/product1.php

 

This was probably a mistake on my part somewhere along the line. Also, if Javascript would be simpler, my teacher recently opened up the extra credit to allow us to use it as well. Again, I really appreciate all of your help.

Link to comment
Share on other sites

Link to post
Share on other sites

Actually, there was a mistake on my part as well once you resolve the issue you were having. To get the value of an input with Jquery, it is .val(), not .value() as I had stated. On to why it didn't quite work for you, that was another mistake on my part. You need two script tags. One is the tag that includes the Jquery file, and another which actually has the script. You had them both in one tag. I didn't tell you any different.

 

The second script tag also needs to be after the content it affects, usually this means just putting it at the end of the document. 

 

You also changed you hidden inputs at the bottom slightly. I'm not sure if you needed to, but we were getting the base price from an input there, so I altered it to also have the current price. Apart from that, it all works pretty well. An issue I saw on the server file was something I think you saw previously, it wouldn't round the value. So I just used the money_format function again. 

 

Here is the link to what I was using to test, source code is at the bottom of the pages https://hazy125.com/randomcrap/LTT/dev/Otaku_MasterRace/

I am good at computer

Spoiler

Motherboard: Gigabyte G1 sniper 3 | CPU: Intel 3770k @5.1Ghz | RAM: 32Gb G.Skill Ripjaws X @1600Mhz | Graphics card: EVGA 980 Ti SC | HDD: Seagate barracuda 3298534883327.74B + Samsung OEM 5400rpm drive + Seatgate barracude 2TB | PSU: Cougar CMX 1200w | CPU cooler: Custom loop

Link to comment
Share on other sites

Link to post
Share on other sites

Everything works. Thank you so much for all of your help! I really appreciate it.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×