1

Edit: I got this to finally work! Below is my example. I hope this helps someone else in the same need.

I have a need for a shipping radio button. One for regular shipping and one for express shipping.

After some help from googling and cale_b here on this form, my problem is as follows:

I have a foreach loop that is getting values from a database and displaying them on a page. I need a radio button selector (or anything that works the same way) to pick which type of shipping the user wants. I need the buy button on each row to have a total that is calculated from another php page.

I can pull all this information from my shipping database and do the calculations and send it back to the page using ajax but I need to be able to dynamically get the price, size, type and shippingType sent and brought back based on each row. Then use that new total cost and assign it to an input field called totalCost for submition.

Here is the html/php code I am using now.

 <div class="details">
    <table class="default">
        <th>Type</th>
        <th>Size</th>
        <th>Price</th>
        <th>Shipping</th>
        <th>Total</th>
        <th>Buy</th>

    <?php
        $getArtDetails = get_tableContentsWhere($con,'prices','artID',$id);
        foreach($getArtDetails as $detail)
        {

    ?>
        <tr>
            <td class="type"><?= $detail['type'] ?></td>
            <td class="size"><?= $detail['size'] ?></td>
            <td class="price">$<?= $detail['price'] ?>.00</td>
            <td>
                <input type="radio" name="shipping_<?= $detail['id'] ?>" class="radio" value="Xpress">Express Shipping
                <input type="radio" name="shipping_<?= $detail['id'] ?>" class="radio" value="Regular">Regular Shipping
                <input type="radio" name="shipping_<?= $detail['id'] ?>" class="radio" value="Free">Free Shipping
            </td>
            <td class="shipping"></td>
            <td>
                <form action="" method="post">
                    <input type="hidden" name="totalCost" value="set by jquery?">
                    <input type="submit" name="submit" value="Buy">
                </form>                                                        
            </td>
        </tr>
    <?php } ?>


    </table>

</div>

Here is the getShipping.php file that returns my total cost.

shipping.php:

<?php
include 'admin/config/functions.php';

$size = $_GET['size'];
$type = $_GET['type'];
$price = $_GET['price'];
$shippingType = $_GET['shippingType'];

$shipping = get_shippingRate($con,$size,$type,$shippingType);

$totalCost = $shipping + $price;

echo $totalCost;

The following script does what I need it to do but with 2 problems 1. When I pick a radio button the value changes for all of them instead of the each one. cale_b I tried your solution here for finding the next TR but it does not return results. In turn does not set the input for submission either 2. The other issue is i need it to send the size, type and price dynamically to my getShipping.php page. I am not sure how to do that either.

<script>
$('input[name^="shipping"]').each(function(index) {
    $(this).on('click', function(){
        var shippingType = $(this).val();
        var size = $(this).closest('tr').find('td.size').text();
        var type = $(this).closest('tr').find('td.type').text();
        var price = $(this).closest('tr').find('td.price').text();
        // I had to set $(this) to equal $this so I could access it within the ajax call as $(this) was referring to itself.
        var $this = $(this);


        $.ajax({
            type: "GET",
            url: "getShipping.php",
            data: 'size=' + size + '&type=' + type + '&shippingType=' + shippingType + '&price=' + price,
            success:function(data){
                //called when successful
                $this.closest('tr').find('td.shipping').html(data);
            },
            error: function(e) {
                //called when there is an error
                console.log(e.message);
            }
        });
    });
});
</script>

So with all the code above, it appears I am close to what I am looking for but need some extra guidance.

Any help to this would be greatly appreciated.

Thanks,

jAC

jAC
  • 3,155
  • 3
  • 18
  • 29
  • Where is your ajax? We need more information to help with this. Or do you NOT really mean ajax, but just jQuery? (Since the value is in your input elements)? – random_user_name Jan 03 '16 at 16:33
  • @cale_b I don't have any any right now that is working. That is what i need help with. I dont know if it should be ajax or jquery. Both are fairly new to me. – jAC Jan 03 '16 at 16:35
  • @cale_b added the scripts i have tried (one jquery and one ajax) – jAC Jan 03 '16 at 16:39
  • OK. Recommend editing the question and removing the AJAX tag, as well as changing it so it does not say "...adding it to PHP variable ...". Also, please review my answer below - if it's off-base / incorrect, let me know (how) so I can fix it. – random_user_name Jan 03 '16 at 16:43
  • @cale_b adding it to a php variable is exactly what i need though, that is why i thought i may need ajax – jAC Jan 03 '16 at 21:33

2 Answers2

2

If I understand your question properly, you don't need AJAX.

First, modify your HTML like so:

    <tr>
        <td><?= $detail['type'] ?></td>
        <td><?= $detail['size'] ?></td>
        <td class="product_price">$<?= $detail['price'] ?>.00</td>
        <td>
            <input type="radio" name="shipping_<?= $detail['id'] ?>" class="radio" value="30">Express Shipping
            <input type="radio" name="shipping_<?= $detail['id'] ?>" class="radio" value="15">Regular Shipping
            <input type="radio" name="shipping_<?= $detail['id'] ?>" class="radio" value="0">Free Shipping
            <input type="hidden" class="shipping_amount" name="shipping_amount_<?php echo $detail['id']" value="">
        </td>
        <?php // Create a "container" for the price ?>
        <td class="shipping"></td>
    </tr>

Then, at the top of your output / in your <head>, add the following code:

// Document Ready - wait until page is loaded
jQuery(function($) {
    // Select all inputs with name starting with "shipping".  Don't need script inside of the loop
    $(document).on('click', 'input[name^="shipping"]',
        function() {
            // Get the price from the clicked input
            var shipping = parseFloat($(this).attr('value'));
            var price = parseFloat($(this).html());
            var total = price + shipping;
            // Find the proper cell, and set the display to the amount
            $(this).closest('tr').find('td.shipping').html(shipping);
            $(this).closest('tr').find('input.shipping_amount').val(shipping);
            $(this).closest('tr').find('input[name^="totalCost"]').val(total);
        }
    );
});

This relies on each "Shipping" being in a table row, and on the shipping display to be in a table cell within that row.

NOTE
The code above has been edited to ALSO support an input that will be passed when the form is submitted. Since that input was not in the original question code, I've made assumptions - look for "shipping_amount".

ADDITIONAL NOTE The above code has been modified to also provide an update to the "totalCost" input in the form.
Please note that a class has been added to the "price" cell (td element).

IF you submit this form this way, you're going to want to also:

  1. Submit which product id is being ordered. This way on form validation (PHP side), you can load the product from the DB and verify the price.
  2. Submit which shipping is being selected. This way you can verify the price of shipping.

In order to do this, your form tags should PROBABLY wrap the whole table, and you should add a hidden input that contains the "product id", so that you can get that info, as well as the selected radio button.

Good luck!

random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • this is close to what I want but i still need the value that is returned assigned to a php variable which is why i think i need ajax. I have to be able to take that result and pass it to a pay pal button which is generated later on. Also notice that my input name is appended with an ID as there can be more than one set of radio buttons in the for loop. It also may not always be a table. Some of the stuff I read was to make it use a class rather than the input type but i was getting too many conflicting messages. – jAC Jan 03 '16 at 21:30
  • Yes! I believe this is going to do exactly what i need! Clever on the setting input hidden field to pass it through. Thank you so much! I will edit to remove the ajax stuff. – jAC Jan 03 '16 at 21:56
  • Hrm... almost does what I want. I need to add the shipping price to the price of the item before it leaves the page. – jAC Jan 03 '16 at 22:04
  • So, as a side comment - it would be **really great** if the original question was clear in this specification. If you need the specific code to make this happen, let me know. Otherwise, I believe all the pieces of the puzzle are in place for you above. (Again - let me know, I will happily make the answer even more robust if need be) – random_user_name Jan 04 '16 at 14:55
  • Ok, let me reword the question with a more accurate example (i have been playing around with what you gave me and some other ajax stuff) – jAC Jan 04 '16 at 17:48
  • the changes are now up for your review. Thanks again. – jAC Jan 04 '16 at 18:16
  • Where are the values of prices for the jQuery to access? You are displaying them in the cells, but jQuery needs to access prices of the products. Having them as an attribute on element or some other element would be useful. Also, **you must validate ALL selections** on the PHP side before saving it. People can manipulate these values, you would never actually want to SHIP something / fulfill an order based on what PHP received from this form (so far). LASTLY, your form does not show which shipping options were selected, which products were selected, etc. You may want to restructure. – random_user_name Jan 04 '16 at 18:58
  • the values of the prices are stored in a database. each row is getting pulled through the foreach loop that i have there. Do you have an example of how you would accomplish this? Validation concerns aside. This does not show my validation as I am just trying to get this to work first, then I will make sure my data is safe. As for the form, again, all i want it to do is put the total cost of shipping plus the price of the item into the input field. I will be doing more with the data once i get this part to work. – jAC Jan 04 '16 at 19:13
  • Does this form need to support multiple products? Let me know, if not, I can get this resolved. Also - why did you unaccept? I've put TONS of energy into constructing this answer for you. – random_user_name Jan 04 '16 at 21:27
  • the unaccept was by accident. I was actually trying to figure out how stackoverflow does it with the voting and accepting as its the same sort of idea i want minus writing the values to a database. It does not have to support multiple products, just what ever is in that row. So what i am doing is adding together the price and the the shipping cost from a database and sending that total through a form. – jAC Jan 04 '16 at 22:54
  • ok, I got this working 95%, please see my edit above in the script section. The only issue I am having now is that when i click on the radio button it changes the Total column for all the items. How do i get it to only change only the row the radio button is in? – jAC Jan 05 '16 at 00:22
  • Ok i got it :) see my edit above for what I did to resolve the issue the way I needed it. Thank you so much @cale_b could not have done it without your help – jAC Jan 05 '16 at 00:44
  • The code has been modified. I'll be honest, at this point, in my understanding of your requirements, I'd personally probably re-structure the code. Please review the changes, as well as my new notes that I have added. Good luck! – random_user_name Jan 05 '16 at 01:20
  • I need to get the shipping cost from the a database and I am not submitting the shipping in the way you think I am. Your solution helped me achieve what I was looking for but still needed the ajax component. Thanks for all of your help on this one. – jAC Jan 05 '16 at 01:32
1

cale_b is right. It doesn't look like you need AJAX here. AJAX is used when you need to communicate with the server, and is usually used for database functions (looking stuff up on the fly, storing a new value, etc).

The point of AJAX is that it communicates with the server, sending data to the server and (optionally) receiving data back from the server, without refreshing the page. An HTML form also sends data to the server, but once the user clicks Submit the current page changes to the "action" page.

In your example, it appears that you need to use a javascript variable, not necessarily a PHP variable. If all you want to do is grab information off the page, store it in a variable, (perhaps perform some math using other values from other fields), and then spit the product back onto the same page -- no server interaction is needed. Javascript/jQuery will do that just fine.

For a better understand of what AJAX is all about, this post has some great beginner examples:

AJAX request callback using jQuery

And here is a good (free) introduction video to AJAX

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111