I have products listing page where all listed products have different form name and id using while loop as mentioned in below piece of code. I want to make so when user clicks on 'Add' button for particular product, then that specific product's form should be submitted using AJAX/jQuery.
product_listing.php
<script language="JavaScript" src="./product_listing.js"></script>
while loop to list products on page {
<form id="frm_add<?php print $rs_list->Fields("pkid"); ?>" name="frm_add<?php print $rs_list->Fields("pkid"); ?>" novalidate>
<input type="hidden" name="hdn_prodpkid" id="hdn_prodpkid" value="<?php print $rs_list->Fields("pkid"); ?>">
... other variables...
<button type="submit" name='btn_addtocart' id='btn_addtocart'>Add</button>
</form>
end of while loop }
I want submitted form's ID so I can fetch input fields' values for that submitted form. But on every form submission I got last form's ID.
So how can I get unique (only submitted) form's ID on JS page? Please advise.
Below code works perfectly when there is a single form to submit. In that case, form id is predefined on both .php and .js pages.
product_listing.js
$(function() {
$("#"+NEED_SUBMITTED_FORM_ID_HERE+" input, #"+NEED_SUBMITTED_FORM_ID_HERE+" select").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
...other code...
},
submitSuccess: function($form, event) {
event.preventDefault();
var hdn_prodpkid = $("input#hdn_prodpkid").val();
... other variables...
$.ajax({
url: "./product_addtocart_p.php",
type: "POST",
data: {
hdn_prodpkid: hdn_prodpkid,
... other variables...
},
cache: false,
success: function(data)
{
...other code...
}
}
});
});
-- UPDATED CODE --
product_listing.js
var id = '';
$(function() {
$("form").submit(function() {
var form = $(this);
var id = form.attr('id');
//alert(id + ' form submitted');
$("#"+id+" input, #"+id+" select").jqBootstrapValidation({
//alert(id + ' form submitted'); // Can't alert ID here
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
var hdn_prodpkid = $("input#hdn_prodpkid").val();
$.ajax({
url: "./product_addtocart_p.php",
type: "POST",
data: {
hdn_prodpkid: hdn_prodpkid
},
cache: false,
}) // End of Ajax
}, // End of submitSuccess
}); // End of jqBootstrapValidation
}); // End of form submit
}); // End of $(function())