Handle submission of forms created dynamically having same class

Posted by user1504383 on Stack Overflow See other posts from Stack Overflow or by user1504383
Published on 2012-07-05T15:14:00Z Indexed on 2012/07/05 15:15 UTC
Read the original article Hit count: 165

Filed under:

i am creating a form for users to comment on each posts displayed through a loop and the form for commenting is also in the same loop. Now i want each comment to be submitted via jquery ajax but each time its taking into account only the first form . Here is my code:-

while($row=mysql_fetch_array($result))
{ ?>
     <?=$row['title']?>
     <h4>Add commment </h4>
<form class="add_comment" method="post">

    <div style="display:none;"><input type="text" name="id" class="id" value="<?=$row['id']?>"/></div>

    <input type="text" name="comment" class="comment"/>
    <input type="submit" name="submit" value="add" class="submit"/>
</form>

<?php
}
?>

And my jquery goes here

$("form.add_comment").submit(function(event) {
            event.preventDefault();

        var comment     =$('.comment').attr('value');
        var id  =$('.id').attr('value');
            $.ajax({
                type: "POST",
                url:  "/add_comment",
                data: "comment="+comment+"&id="+id,
                success: function() {
                    location.reload();
                }
            });
            return false;
        });`enter code here`

i understood the error that it selects the first one by default but couldnt fix it up plz help me

© Stack Overflow or respective owner

Related posts about jquery-ajax