0

I have a strange problem here. I am processing data via AJAX from a table loaded inside while loop and when the data is successfully processed the table gets reloaded with new data via AJAX and JSON. The problem is that when the new table is loaded and I click the same submit button from any row again then this time instead of processing it via AJAX it works as a normal submit button and refreshes the page. Then when the page is refreshed the submit button works via AJAX again. Why is it not working with AJAX when the table was reloaded via AJAX after previous operation via AJAX when in both the tables the parameters used are exactly the same? My codes are below. Please tell my what's wrong here and what's the solution for this.

membership.php

<div class="row">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <h3 class="card-title">Memberships List</h3>
        </div>
        <div class="card-body table-responsive p-0">
          <table class="table table-hover table-striped" id="mbslist">
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Daily Capping</th>
              <th>Commission</th>
              <th>Payout</th>
              <th>Payout %</th>
              <th>Cost</th>
              <th>Status</th>
              <th>Action</th>
            </tr>
            <?php
              $i = 1;
              $mem = $pdo->prepare("SELECT * FROM memberships");
              $mem-> execute();
              while($m = $mem->fetch()){ extract($m);
                if($mem_status == 'enabled'){
                  $statusColor = "text-success";
                  $btn = "btn-danger";
                  $status = "disabled";
                  $btnVal = "Disable";
                }else{
                  $statusColor = "text-danger";
                  $btn = "btn-success";
                  $status = "enabled";
                  $btnVal = "Enable";
                }
            ?>
              <tr>
                <td><?php echo $i; ?></td>
                <td><span style="color: <?php echo $mem_color; ?>"><?php echo $mem_name; ?></span></td>
                <td>&#8377;<?php echo $mem_daily_capping; ?></td>
                <td>&#8377;<?php echo $mem_earn_amount; ?></td>
                <td>&#8377;<?php echo $mem_min_payout; ?></td>
                <td><?php echo $mem_payout_percent; ?>%</td>
                <td><?php if($mem_price == '0.00'){ echo "Free"; }else{ echo "&#8377;$mem_price"; } ?></td>
                <td><span class="<?php echo $statusColor; ?>"><?php echo ucfirst($mem_status); ?></span></td>
                <td>

                  <form method="post" action="">
                    <input type="hidden" value="<?php echo $mem_id; ?>" class="memid">
                    <input type="hidden" value="<?php echo $status; ?>" class="status">
                    <input type="hidden" value="memstatus" class="type">
                    <?php if($mem_id != 1){ ?>
                      <input type="submit" class="btn <?php echo $btn; ?> mbslist" value="<?php echo ucfirst($btnVal); ?>">
                    <?php } ?>
                    <a href="?mem=<?php echo $mem_id; ?>&action=edit" class="btn btn-primary">Edit</a>
                  </form>
                </td>
              </tr>
            <?php $i++; } ?>
          </table>
        </div>
      </div>
    </div>
    <div class="message"></div>
  </div>

AJAX Code

// Set Membership Status
$(document).ready(function(){
    $(".mbslist").click(function() {
      var dataString = {
        id: $(this).closest('tr').find('.memid').val(),
        type: $(this).closest('tr').find('.type').val(),
        status: $(this).closest('tr').find('.status').val()
      };
      console.log(dataString);
      $.ajax({
        type: "POST",
        dataType : "json",
        url: "processes/memberships.php",
        data: dataString,
        cache: true,
        beforeSend: function(){
          $('.message').hide();
          $('.overlay').fadeIn();
        },
        success: function(json){
          $('.message').html(json.status);
          setTimeout(function(){
            $('.overlay').fadeOut();
            $('.message').fadeIn();
            $('#mbslist').html(json.table).fadeIn();
          }, 2000);
        }
      });
      return false;
    });
});

processes/memberships.php

<?php
include('../../config/db.php'); include('../../functions.php');

$memid  = (!empty($_POST['id']))?$_POST['id']:null;
$type   = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;

$color   = (!empty($_POST['color']))?$_POST['color']:null;
$name    = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount  = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay  = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price   = (!empty($_POST['price']))?$_POST['price']:null;

if($_POST){
  if($type == 'memstatus'){
    $update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
    $update-> bindValue(':status', $status);
    $update-> bindValue(':id', $memid);
    $update-> execute();

    if($update){
      $pro = $pdo->prepare("SELECT * FROM memberships");
      $pro-> execute();

      $table = "<table class='table table-hover table-striped' id='mbslist'>
                  <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Daily Capping</th>
                    <th>Commission</th>
                    <th>Payout</th>
                    <th>Payout %</th>
                    <th>Cost</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>";

        $i = 1;
        while($p = $pro->fetch()){ extract($p);
          if($mem_status == 'enabled'){
            $statusColor = "text-success";
            $btn = "btn-danger";
            $status = "disabled";
            $btnVal = "Disable";
          }else{
            $statusColor = "text-danger";
            $btn = "btn-success";
            $status = "enabled";
            $btnVal = "Enable";
          }
          if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
        $table .= "<tr>
                    <td>".$i."</td>
                    <td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
                    <td>&#8377;".$mem_daily_capping."</td>
                    <td>&#8377;".$mem_earn_amount."</td>
                    <td>&#8377;".$mem_min_payout."</td>
                    <td>".$mem_payout_percent."%</td>
                    <td>".$mp."</td>
                    <td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
                    <td>
                      <form method='post' action=''>
                        <input type='hidden' value=".$mem_id." class='memid'>
                        <input type='hidden' value=".$status." class='status'>
                        <input type='hidden' value='memstatus' class='type'>
                        <input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
                        <a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
                      </form>
                    </td>
                  </tr>";
        $i++;
      }

      $table .= "</table>";
     echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
   }else{
     echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
   }
  }
}
  • Possible duplicate of https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – CBroe Aug 01 '18 at 11:00

2 Answers2

0

Your submit button will try to submit form normally when you click it. So just use "event.preventDefault() " as below so your button wont trigger normal form submission and now wont load the page.

$(".mbslist").click(function(event) {
  event.preventDefault();
}
Surya Neupane
  • 906
  • 10
  • 20
0

Modify your processes/memberships.php with following code:

$memid  = (!empty($_POST['id']))?$_POST['id']:null;
$type   = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;

$color   = (!empty($_POST['color']))?$_POST['color']:null;
$name    = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount  = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay  = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price   = (!empty($_POST['price']))?$_POST['price']:null;

if($_POST){
  if($type == 'memstatus'){
    $update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
    $update-> bindValue(':status', $status);
    $update-> bindValue(':id', $memid);
    $update-> execute();

    if($update){
      $pro = $pdo->prepare("SELECT * FROM memberships");
      $pro-> execute();

      $table = "<table class='table table-hover table-striped' id='mbslist'>
                  <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Daily Capping</th>
                    <th>Commission</th>
                    <th>Payout</th>
                    <th>Payout %</th>
                    <th>Cost</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>";

        $i = 1;
        while($p = $pro->fetch()){ extract($p);
          if($mem_status == 'enabled'){
            $statusColor = "text-success";
            $btn = "btn-danger";
            $status = "disabled";
            $btnVal = "Disable";
          }else{
            $statusColor = "text-danger";
            $btn = "btn-success";
            $status = "enabled";
            $btnVal = "Enable";
          }
          if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
        $table .= "<tr>
                    <td>".$i."</td>
                    <td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
                    <td>&#8377;".$mem_daily_capping."</td>
                    <td>&#8377;".$mem_earn_amount."</td>
                    <td>&#8377;".$mem_min_payout."</td>
                    <td>".$mem_payout_percent."%</td>
                    <td>".$mp."</td>
                    <td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
                    <td>
                      <form method='post' action=''>
                        <input type='hidden' value=".$mem_id." class='memid'>
                        <input type='hidden' value=".$status." class='status'>
                        <input type='hidden' value='memstatus' class='type'>
                        <input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
                        <a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
                      </form>
                    </td>
                  </tr>";
        $i++;
      }

      $table .= "</table>";
     echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
   }else{
     echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
   }
  }
}
?>
<script>
// Set Membership Status
$(document).ready(function(){
    $(".mbslist").click(function() {
      var dataString = {
        id: $(this).closest('tr').find('.memid').val(),
        type: $(this).closest('tr').find('.type').val(),
        status: $(this).closest('tr').find('.status').val()
      };
      console.log(dataString);
      $.ajax({
        type: "POST",
        dataType : "json",
        url: "processes/memberships.php",
        data: dataString,
        cache: true,
        beforeSend: function(){
          $('.message').hide();
          $('.overlay').fadeIn();
        },
        success: function(json){
          $('.message').html(json.status);
          setTimeout(function(){
            $('.overlay').fadeOut();
            $('.message').fadeIn();
            $('#mbslist').html(json.table).fadeIn();
          }, 2000);
        }
      });
      return false;
    });
});
</script>

Hope this might help you.

NightOwl
  • 329
  • 2
  • 20
  • and this AJAX code will load inside each and every table row in while loop? Do you really think its a good idea? Also, this ain't working. – Shubham Jha Aug 01 '18 at 11:18
  • Wait.. I modified it and placed it inside `$table` variable as an extension to the variable. Now its working. But is this really a good idea to do this? – Shubham Jha Aug 01 '18 at 11:25
  • I have corrected your answer for the way it helped me and accepted it as its currently solving my problem. However, I can't upvote it as I am not sure if this is the best approach as a solution to the problem. Thanks anyway. At least it works well for now. The way you answered didn't actually solve the issue but gave me an idea to work it out. – Shubham Jha Aug 02 '18 at 19:58