0

I have this page where i load products by getting them as json from my php and putting them in html in js side like so :

function getProducts(type)
{
$.ajax({
    type:"POST",
    url:"backend/getProducts.php",
    data: {
        category: type
    },
    success:function(data){
        var response = jQuery.parseJSON(data);
        var products = "";

        for(var i = 0; i < response.data.length; i++)
        {
            products += "<div class='col-md-12 product center-block'>";
            products += "<div class='col-md-4 product-photo-container' data-aos='fade-right'><img src='images/"+response.data[i].Picture+"' class='product-photo img img-responsive'/></div><div class='col-md-8 products-text-container' data-aos='fade-left'>";
            products +=     "<h3 class='product-name'>"+response.data[i].Name+"</h3>";
            products +=     "<p class='product-description'><span class='bold'>Description : </span>"+response.data[i].Description+"</p>";
            products +=     "<h5 class='product-color'><span class='bold'>Color : </span>"+response.data[i].Color+"</h5>";
            products +=     "<h5 class='product-price'><span class='bold'>Price : </span>"+response.data[i].Price+"</h5>";
            products +=     "<form method='post' class='add-to-cart-form'><input type='hidden' name='id' value='"+response.data[i].ID+"'><div class='input-group'><input type='number' class='quantity form-control' placeholder='Quantity'><div class='input-group-btn'><button class='btn btn-default' type='submit'>Add to Cart</button></div></div></form>";
            products += "</div></div>";
        }

        if(response.data.length == 0)
        {
            products += "<div style='min-height: 60vh'><h3 class='text-center' style='margin-top: 20vh'>No Products Found</h3></div>"
        }
        $("#shop-section").html(products);
    }
});

}

but when i try to catch the add-to-cart-form on submit to add the item to cart it just submits the form anyway even though i have e.preventDefault().

$(".add-to-cart-form").on('submit',function(e){
    e.preventDefault();
    // do stuff here
});

how can i fix this ? Thanks

Ayman H
  • 1
  • 2
  • Read up on ***[Event Delegation](http://learn.jquery.com/events/event-delegation/)*** – charlietfl May 31 '17 at 23:06
  • sorry i honestly searched and could not find the question on stackoverflow. The link helped thank you sooo much it has been bugging me since forever ! cheers @charlietfl – Ayman H May 31 '17 at 23:11

0 Answers0