Albert Henderson
Albert Henderson

Reputation: 47

Differentiate multiple form on AJAX

I have a php page with multiple form inside.

<form id="form_<?php echo $rowProduct['Product_ID'];?>">
    <a id="wh_<?php echo $rowProduct['Product_ID'];?>"><i class="fal fa-heart"></i></a>
    <input type="hidden" name="PID_<?php echo $rowProduct['Product_ID'];?>" value="<?php echo $rowProduct['Product_ID'];?>">
    <input type="hidden" name="mail_<?php echo $rowProduct['Product_ID'];?>" value="<?php echo $rowProduct['Mail'];?>">

Those form generate from looping through all data on MySQL. Every form and input has their unique id by Product_ID.

Below is ajax script to submit data to database.

<script>
    $('[id^=wh_]').click(function(e) {
        $.ajax({
            url: 'submit.php',
            type: 'POST',
            data: $("[id^=form_]").serialize(),
            success: function(data) {
                alert('Success add item');
            }
        });
        e.preventDefault();
    });
</script>

Currently this code successfull to insert data to MySql, but the submited data always be the last form only whatever which submit button clicked. I'm using AJAX to submit those forms to achieve a form submit without refreshing the php page.

Much appreciate for every help.

Upvotes: 0

Views: 53

Answers (1)

brk
brk

Reputation: 50291

Try by changing this data: $("[id^=form_]").serialize(), to

data: $(this).closest('form').serialize()

Upvotes: 1

Related Questions