Search code examples
phpjquerywhile-loopshow-hide

Trying to hide specific div in jquery in php while loop


I have this form being outputted from a PHP while loop :

echo '<div id="postCont" class="postCont'.$pid.'" style="block;">
    <div id="clLink">
      <a id="clLink" href="'.$plink.'" target="_blank"" title="'.$ptitle.'">'.$ptitle.'</a>
    </div>
    <div id="clDate">Posted on '.$pdate.'</div>
    <div id="clDesc">'.$pdesc.'</div>

    <form method="post" class="ibadForm">
        <input type="hidden" name="id" value="'.$pid.'">
        <input type="hidden" name="hiddenBad" value="yes">
        <input type="image" src="../img/bad.png" name="subBad" value="Bad" class="bad">
    </form>
</div>';

I am trying to remove the individual .postCont when the ibadForm is clicked with jquery.

$(".ibadForm").submit(function(e) {
     var url = "add_form.php"; 
     var id = <?php echo $pid?>;
     $.ajax({
          type: "POST",
          url: url,
          data: $(this).serialize(),
          success: function(data)
         {
             $('.postCont' + id).hide();
         }
     });
     e.preventDefault();
 });

It submits the form to add_form.php fine but doesn't hide the postCont. If I remove the id from the class then it hides all post Cont's. Can anyone tell me where I am going wrong?


Solution

  • You could use closest() to get the parent div then hide it using hide() method like :

    $(".ibadForm").submit(function(e) {
      var url = "add_form.php"; 
      var id = <?php echo $pid?>;
      var _this = $(this);
    
      $.ajax({
        type: "POST",
        url: url,
        data: $(this).serialize(),
        success: function(data)
        {
          _this.closest('.postCont').hide();
        }
      });
      e.preventDefault();
    });
    

    NOTE : You should store the $(this) object that refer to the clicked form in some variable (_this in my example) then use it inside the success callback since $(this) inside callback doesn't refer no more to the form, e.g :

    _this.closest('.postCont').hide();
    

    Hope this helps.