I have a list of items which is dynamically updated via an ajax call whenever a new item is added. There’s a comment form included in each of these list items that has a comment field and a hidden field which indicates which item has been commented on.
I’m using the jquery form plugin to submit these forms using ajax. The problem I keep running into is that the forms are not recognized by the plugin so they run normally (posting and redirecting to ajax/comment.php). After doing some digging I think this is because the forms are being loaded dynamically and the script can’t ‘see’ them. I’ve read about eval() being a possible solution to get the script to run correctly. Right now the code executes correctly if I don’t use ajax to populate the page.
<script>
$(document).ready(function() {
var options = {
url: 'ajax/comment.php',
};
$('.commentsubmit').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
</script>
If the forms are loaded dynamically, change
.submitto this:This will delegate the
submitevent to any.commentsubmitforms that may not be added to the DOM at the time you call.on.On an unrelated note, use
e.preventDefault(), notreturn false: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/