0

I have a shopping cart which uses PHP. When a person adds something to their cart, the relevant code is done at the top of cart.php, meaning they have to leave the product page as they add something to cart, and end up having to press the back button if they want to do more.

How do I execute PHP/SQL code when a user clicks "add to cart", but without redirecting them to a new page? I think Jquery/JSON is needed here, but I don't know the first thing about that. Something like the below:

//product page
<input type="button" value="3"/>
//when the button is clicked, do some SQL/PHP based on the value on the same page

Originally, I had:

//product page
<form action="./cart.php" method="post">
    //some code for user to select whats to be submitted
    <input type="submit"/>
</form>
...
//cart page
//some logic relevant to taking value from product page and adding to cart
//then display cart contents

The problem is that it takes them to a new page when I'm positive the logic can be done on the same page onclick of button.

1
  • 4
    Can I gently suggest that you do a little more thorough background education first? Learning on-the-project can definitely be fun, but it also makes it easy to leave gaps in your knowledge that can bite you hard in the future. There's a lot that you don't know at this point that you probably ought to if you're building a shopping cart. Commented Jan 31, 2014 at 18:20

2 Answers 2

1

Do a POST request with jQuery,the page doesn't load since it is ajax..

$('input[type="submit"]').on('click',function(){
    var data = $('your_input_element').val();
    $.post('./cart.php',{"data" :data},function(response) 
    {
        console.log(response);
    });
});

OR:

Give a target to your form to an iframe which is hidden

//product page
<form action="./cart.php" method="post" target="iframe_target">
    //some code for user to select whats to be submitted
    <input type="submit"/>
</form>
<iframe id="iframe_target" name="iframe_target" src="#" style="display:none;"></iframe> 
Sign up to request clarification or add additional context in comments.

2 Comments

Can an iframe src be a .php? I thought it was strictly for .html.
Yes you can, but i would prefer first method, check this link for more : css-tricks.com/snippets/html/post-data-to-an-iframe
1

You'd need an ajax-style handler in javascript.

Using jquery you could handle the click and send the cart data to a php script:

$('button').click(function(e){
  $.post('url', {product_id:$(this).val(), function(){ // success });
});

Comments

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.