简体   繁体   中英

Submitting Forms from Ajax Response

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 .submit to this:

$(document).on('submit', '.commentsubmit', function () {

This will delegate the submit event to any .commentsubmit forms that may not be added to the DOM at the time you call .on .

On an unrelated note, use e.preventDefault() , not return false : http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM