简体   繁体   中英

How can I send the value of the id through ajax and PHP

I want to pass value of the id of the product to cart.php by using AJAX and display it in a div.cart in index.php but I have no idea how. please help.

Product

Product Description

Add to Cart
 $('a').on('click', function(e){ $.ajax({ url: data: }) e.preventDefault(); }); 

Of course you can :) !

So first, let's get things straight. You're showing a list of products as <div class="thumbnail"> form, right ? So your PHP/HTML should look a bit like this in reality :

<?php
foreach($database_recordset as $row) {
    echo '
    <div class="thumbnail>
        <img src="'.$row['img_src'].'" alt="'.$row['img_alt'].'" />
        <div class="caption">
            <h4>'.$row['product_name'].'</h4>
            <p>'.$row['product_description'].'</p>
            <a id="p-'.$row['id'].'" onclick="addCart(this)">Add to Cart</a>
        </div> <!-- You were missing a /div here if I guessed right the structure -->
    </div>';
}
?>

so I simply labelled the link p-#ID where #ID is the id of the product from the database and added an onclick event with this as the argument. Now you need a function addCart that will contain the AJAX request.

<script type="text/javacscript">
function addCart(elm) {
    // First we need the clean ID of the product
    var id = elm.id.split('-')[1]; // We split with '-' as separator and take the second element of the resulting array
    $.ajax({
        url: "cart.php",
        type: "POST", // or GET whatever but POST is usually better
        data: { id: id },
        success: function(response) {
            if (response.status == 'OK') { // You should always test the response of an ajax request
                // show a message, update the cart icon or whatever
            }
        }
    });
}
</script>

you need to modify you code something like this. Href need to be removed else it will redirect you on that page. Give below is a sample of your code

<div class="thumbnail>
<img src="" alt="" />
<div class="caption">
<h4>Product</h4>
<p>Product Description</p>
<a id="id=(id from table products)">Add to Cart</a>
</div>

$('a').on('click', function(e){
$.ajax({
url: cart.php
data:{id:$(this).attr("id")}
})
e.preventDefault();
});

You need to stop the browser following the link, then make an ajax request and insert the response into the target div.

You can use jquerys load method to acheive that in a single call:

$('a.clickme').click(function(ev){
    ev.preventDefault();
    $('div.cart').load($(this).attr('href'));
});

Note i added a class to the link, else your code would capture all link clicks including site navigation etc

<a href="cart.php?id=(id from table products)" class="clickme">Add to Cart</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM