0

I'm fairly new to php and ran into an issue adapting someone else's program. I am trying to implement a shopping cart style php and javascript program. The shopping cart accepts new entries by POSTing values by way of a submit button including id, quantity, name and price.

    <form method="post" style="border:0px solid yellow;" ><fieldset>
    <input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
        <input type="hidden" name="my-item-id" value="1" />
        <input type="hidden" name="my-item-name" value="apples" />
        <input type="hidden" name="my-item-price" value="2" />
        <input type="hidden" name="my-item-qty" value="1" size="3" />


<input id="apples" type="submit" name="my-add-button" class="add" value="&nbsp"/>Apples - $2

</fieldset></form>

The cart removes items by way of GET commands through the php file

    if($_GET['jcartRemove'] && !$_POST) {
        $this->remove_item($_GET['jcartRemove']);
    }

This GET command can be triggered through

    <a href="index.php?jcartRemove=apples">no more apples</a>

But this will only trigger once. What I want is to have a list of items

  • apples
  • oranges
  • bananas

and when one is selected and added to the cart through the form post method, the other two are automatically removed from the cart. Is there a way to use AJAX to push the jcartRemove function and remove two items by their ID?

Any help would be appreciated on this.

1 Answer 1

1

Rather than making multiple AJAX calls, you'd be better off modifying your PHP and allowing the remove function to accept an array instead of just one item. Then you could pass it one or many items to remove all at once.

For example:

if($_GET['jcartRemove'] && !$_POST) {
    if (is_array($_GET['jcartRemove'])) {
        foreach($_GET['jcartRemove'] as $item) {
             $this->remove_item($item);
        }
    } else {
        $this->remove_item($_GET['jcartRemove']);
    }
}

Your link would look like this with multiple items:

<a href="index.php?jcartRemove[]=apples&jcartRemove[]=bananas">no more apples or bananas</a>

Because we're checking if jscartRemove is an array, you can still pass it a single item like you always have and it will continue to work as well.

Sign up to request clarification or add additional context in comments.

3 Comments

Having this approach of considering both the html/js/ajax and php as tools to fulfill your requirements is core.
Thank you for you help, but the code above causes the page to display as blank.
And it does!! Thank you so greatly! I should have caught that typo myself, but Friday and all...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.