Shubham Jha
Shubham Jha

Reputation: 63

Returning Table data with JSON not working

I am trying to return the table data with JSON and update the current table so that when the data is inserted I can see a live update without needing to refresh the page each time to make the workings faster. I tried the following but its not returning the new table.

HTML

<div class="table-responsive">
        <table class="table table-striped" id="pinReqHist">
          <tr>
            <th>ID</th>
            <th>Amount</th>
            <th>Request Date</th>
            <th>Status</th>
          </tr>
          <?php
            while($pin = $pinReq->fetch()){ extract($pin);
              if($pr_status == 'approved'){
                $statusColor = "text-success";
              }else if($pr_status == 'denied'){
                $statusColor = "text-danger";
              }else{
                $statusColor = "text-warning";
              }
          ?>
            <tr>
              <td><?php echo $pr_id; ?></td>
              <td><?php echo $pr_amount; ?></td>
              <td><?php echo date('jS F, Y (h:i a)', strtotime($pr_date)); ?></td>
              <td><span class="<?php echo $statusColor; ?>"><?php echo $pr_status; ?></span></td>
            </tr>
          <?php } ?>
        </table>
      </div>

jQuery

$("#requestPin").click(function() {
    var form = document.requestPin;
    var dataString = $(form).serialize();
    $.ajax({
      type: "POST",
      dataType : "json",
      url: "processes/request-pin.php",
      data: dataString,
      cache: true,
      beforeSend: function(){
        $("#requestPin").html("Please wait...");
        $('.message').hide();
      },
      success: function(json){
        $('.message').html(json.status).fadeIn();
        $("#requestPin").html("Request");
        if($('.message').find('#responseBox').hasClass('alert-success')){
          $('#wallet').html('&#8377;' + json.bal);
          $('#pinReqHist').html(json.table);
        }
      }
    });
    return false;
  });

request-pin.php

<?php
session_start();
include('../config/db.php');
$msg = null;
$userid = (!empty($_SESSION['loggedin']))?$_SESSION['loggedin']:null;

$amount = (!empty($_POST['amount']))?$_POST['amount']:null;

if($_POST){
  $balance = $pdo->prepare("SELECT wal_balance FROM wallet WHERE wal_user = :user");
  $balance-> bindValue(':user', $userid);
  $balance-> execute();
  $bal = $balance->fetch();

  if($amount == ''){
    $msg = "<div class='alert alert-danger' id='responseBox'>Amount is required.</div>";
    echo json_encode(array('status' => $msg, 'bal' => number_format($bal['wal_balance'],2,'.',',')));
  }else if(!ctype_digit($amount)){
    $msg = "<div class='alert alert-danger' id='responseBox'>Please enter only numbers.</div>";
    echo json_encode(array('status' => $msg, 'bal' => number_format($bal['wal_balance'],2,'.',',')));
  }else{
    if($bal['wal_balance'] < $amount){
      $msg = "<div class='alert alert-danger' id='responseBox'>Insufficient balance.</div>";
      echo json_encode(array('status' => $msg, 'bal' => number_format($bal['wal_balance'],2,'.',',')));
    }else{
      $insert = $pdo->prepare("INSERT INTO pin_request(pr_user, pr_amount)VALUES(:user, :amt)");
      $insert-> bindValue(':user', $userid);
      $insert-> bindValue(':amt', $amount);
      $insert-> execute();

      if($insert){
        $update = $pdo->prepare("UPDATE wallet SET wal_balance = wal_balance-".$amount." WHERE wal_user = :user");
        $update-> bindValue(':user', $userid);
        $update-> execute();

        $wallet = $pdo->prepare("SELECT wal_balance FROM wallet WHERE wal_user = :user");
        $wallet-> bindValue(':user', $userid);
        $wallet-> execute();
        $wal = $wallet->fetch();

        $pinReq = $pdo->prepare("SELECT * FROM pin_request WHERE pr_user = :user");
        $pinReq-> bindValue(':user', $userid);
        $pinReq-> execute();

        $table = "<table class='table table-striped' id='pinReqHist'>
                    <tr>
                      <th>ID</th>
                      <th>Amount</th>
                      <th>Request Date</th>
                      <th>Status</th>
                    </tr>";

        while($pin = $pinReq->fetch()){ extract($pin);
          if($pr_status == 'approved'){
            $statusColor = "text-success";
          }else if($pr_status == 'denied'){
            $statusColor = "text-danger";
          }else{
            $statusColor = "text-warning";
          }
          $table .= "<tr>
                      <td>".echo $pr_id."</td>
                      <td>".echo $pr_amount."</td>
                      <td>".echo date("jS F, Y (h:i a)", strtotime($pr_date))."</td>
                      <td><span class='".$statusColor."'>".echo $pr_status."</span></td>
                    </tr>";
        }

        $table .= "</table>";

        $msg = "<div class='alert alert-success' id='responseBox'>Pin request sent!</div>";
        echo json_encode(array('status' => $msg, 'bal' => number_format($wal['wal_balance'],2,'.',','),
                               'table' => $table));
      }else{
        $msg = "<div class='alert alert-danger' id='responseBox'>Server Error! Please try again.</div>";
        echo json_encode(array('status' => $msg, 'bal' => number_format($bal['wal_balance'],2,'.',',')));
      }
    }
  }
}

?>

I searched but couldn't find what mistake I am making. Please help. Also, if anybody would like to make any suggestion regarding any code improvements if required are welcomed and will be highly appreciated.

Upvotes: 0

Views: 102

Answers (1)

Shubham Jha
Shubham Jha

Reputation: 63

Ah! I got the solution. I was making a silly mistake here. Posting the answer to help someone in future if anyone visits this question.

In request-pin.php page inside the while loop I had put echo which actually was an error. Since everything here was already inside a PHP variable $table I didn't need to put echo here. The changes made here were:

Replaced this

$table .= "<tr>
                <td>".echo $pr_id."</td>
                <td>".echo $pr_amount."</td>
                <td>".echo date("jS F, Y (h:i a)", strtotime($pr_date))."</td>
                <td><span class='".$statusColor."'>".echo $pr_status."</span></td>
           </tr>";

With this

$table .= "<tr>
               <td>".$pr_id."</td>
               <td>".$pr_amount."</td>
               <td>".date("jS F, Y (h:i a)", strtotime($pr_date))."</td>
               <td><span class='".$statusColor."'>".$pr_status."</span></td>
           </tr>";

Upvotes: 1

Related Questions