javascript - prevent jQuery post request to fires mulitple times -
i have web shop users can add together products there cart 1 button, remain on catalog page (where products listed). using jquery , ajax. weird thing when press button forms submitted. not want!
$(function() { $('form').submit(function (event) { event.preventdefault(); var $form = $(this), formdata = $form.serialize(), url = $form.attr('action'); $.post(url, formdata); }); });
i understand can't utilize single class this, since submit them all, ids not useful since can have on 50 products on page , lot of duplicated work.
so there solutions this?
thanks in advance
the code show should work in isolation, either code not beingness nail (due error on page), or not connecting per-product forms (e.g. if loaded dynamically).
if forms loaded dynamically, suspect may be, need utilize delegated event handler, attached non-changing ancestor of forms (document
default)
e.g.:
$(function() { $(document).on('submit', 'form', function (event) { event.preventdefault(); var $form = $(this), formdata = $form.serialize(), url = $form.attr('action'); $.post(url, formdata); }); });
it works listening submit
event bubble ancestor, then applies jquery form
selector, then applies function matching elements caused event, work on forms added page dynamically.
if not case, please provide rest of code , sample of page's html (from browser save-as, not source).
javascript jquery ajax forms post
No comments:
Post a Comment