Javascript – AJAX/Javascript Get Submitted Form Data

ajaxjavascriptjquery

In javascript I am creating multiple forms and inputting into html us ajax/js like this:

function addProduct(product) {
                    var html = '';
                    html += '<div>'
                    html += '<form id="product-form">';
                    html += '<div class="city">'+product['product_name']+'</div>'
                    html += '<div class="state">'+product['product_price']+'</div>'
                    html += '<input type="hidden" name="product_id" value="'+product['product_id']+'" id="product_id" >'
                    html += '<a href="#" class="whiteButton submit" id="view-product-button" >View</a>'
                    html += '</form>'
                    html += '</div>'
                    var insert = $(html);
                    $('#main').append(html);
                }

Multiples of these forms are created with different product_ids. The problem I am running into is getting the values of just that form. I am able to correctly identify the form that was submitted but I am not sure out to the the product_id from the input. So far I have this:

$('#main').on('submit', '#product-form', function() {

                    var product_id = $('?????').val()

                });

How can I get the product id and other related data from the form that was submitted?

Best Answer

Use class instead of id for forms and use submit button instead of "a tag", then make your submit function like this

$('.form_class').on('submit', function(e){
    e.preventDefault();
    var form = $(this);
    var formUrl=form.attr('action');
    var product_id = $('#product_id', form).val();

    $.ajax({
        type: "POST",
        url: formUrl,
        data: product_id, // or use form.serialize();
        success: function(data){
            // code goes here;
        },
        error:function (xhr, ajaxOptions, thrownError){
            // code goes here;
        }
    });
});