javascript - Extract a dinamic variable from an Ajax created element out of a foreach loop and perform another jQuery/Ajax call -
in profile.php there main elements can comment clicking post button. comments display in foreach loop. each comment has id created dynamically $comment->id
. when new comment made, displayed in page without need refresh through ajax function. each comment has delete button has id
of comment itself. comment can deleted without need of refreshing page using jquery , ajax. problem when new comment has been created ajax , want delete new comment without refreshing page (because there no edit feature). event bind newly created element jquery i’m using .on
method not working. problem newly created element ajax event bind, jquery function has outside foreach loop. when outside foreach loop can’t access variable $comment->id
(dynamically created) serves 2 purposes, create dinamic #id
delete <p>
tag can targeted jquery, , pass data through ajax delete_comment.php comment can erased database. in posts here in forum learned can variables outside loop creating array, feeding it, , extracting them. works, not ajax, page has refreshed array updated. how can extract foreach loop $comment->id
, new created comment ajax can event bind element jquery , , after new comment has been created ajax, being able delete using ajax well.
many thanks.
my code:
profile.php
<div> main element <script> //process comment ajax $('body').on('click','#post<?php echo $main_element->id;?>',function(){ //create new comment ajax through comment_creation.php }); </script> <?php foreach($comments $comment) { ?> <!-- <div> new ajax comment created here </div> <p id="deletion<?php echo $comment->id; ?>">delete</p> --> <div> comment x </div> <p id="deletion<?php echo $comment->id; ?>">delete x</p> <div> comment y </div> <p id="deletion<?php echo $comment->id; ?>">delete y</p> <div> comment z </div> <p id="deletion<?php echo $comment->id; ?>">delete z</p> <script> $("body").on('click','#deletion<?php echo $comment->id; ?>',function(){ //delete comment using ajax passing $comment->id. delete_comment.php //works elements loaded in dom, not new ajax comments. }); </script> <?php } ?> <script> /* come way here access $comment->id outside foreach of new comment created through ajax can targeted jquery , deleted using ajax well. using array, feeding it, , extracting $comment->id of new ajax comment works if page refreshed. */ </script> </div>
Comments
Post a Comment