yii2renderajaxform

renderAjax failed to return data


I did this in the past year and it works just fine. Until recently I encounter this problem which I don't know what caused it.

Here I'm trying to pass supplierID from a (1)form through (2)ajax javascript and return the (3)data from AdminController to a (4)div in the same view

(1)form:-

<?php $form = ActiveForm::begin([
 'id'=>'chatform'
]);?>
<div class="box-body">
 <table id="example1" class="table table-bordered table-striped">
  <thead>
  <tr>
   <th>No</th>
   <th>Supplier</th>
   <th>Option(s)</th>
  </tr>
  </thead>
  <tbody>

  <?php 
  for($x = 0; $x < count($supplierChatInfoListTable); $x++){ ?>  

  <tr>
   <td>
    <?=$x+1?>
    <div class="form-group">
     <input type="hidden" name="supplierID" id="supplierID" class="form-control" 
      value="<?=$supplierChatInfoListTable[$x]['supplierID']?>" style="width: 50px">
    </div>
   </td>
   <td >
    <h4><?=$supplierChatInfoListTable[$x]['supplierFirstname']?></h4>
   </td>
   <td>
    <button type="button" class="btn btn-primary btnchat"><i class="fa fa-edit"></i></button>
   </td>
  </tr>

  <?php } ?>

  </tbody>
  <tfoot>
  <tr>
   <th>No</th>
   <th>Supplier</th>
   <th>Option(s)</th>
  </tr>
  </tfoot>
 </table>
</div>
<?php ActiveForm::end();?>

and here is my (2)javascript running in the same view:-

<?php
$urproudcode= Url::to(['admin/chatinfo2pass']);

$this->registerJs("
 $(function(){
  $('.btnchat').click(function(){
    var supplierID = $('#supplierID').val();
    $.ajax({
      'url':'".$urproudcode."',
      'data':{supplierID:supplierID},
      'method':'POST',
      beforeSend: function (xhr) {
        $.blockUI({
          message: 'Processing...',
          css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
          }
        });
      },
      'success':function(data){
        $('.chatmessages').html('Success');
        if(data == 'false'){
          $.unblockUI();
          $('.chatmessages').html('Data False');
        }else{
          $.unblockUI();
          $('.chatmessages').html(data);
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
        $.unblockUI();
        $('.chatmessages').html('Failed');
        console.log(data);
      }
    });
   });
  });
 ");
?>

(3)div with class=chatmessages in the same view

<div class="col-md-8 chatmessages">

</div>

(4)actionChatinfo2pass in AdminController

public function actionChatinfo2pass()
{
    $postData = \Yii::$app->request->post('supplierID');

    $supplierID = intval($postData);

    // fetch all supplier for chat
    $supplierChatInfoListTable = SupplierProfile::find()
    ->select(['supplier_profileID AS supplierID','supplier_profile.first_name AS supplierFirstname', 
    'supplier_profile.middle_name AS supplierMiddlename', 'supplier_profile.last_name AS 
    supplierLastname', 'login_profile.login_profileID AS loginID', 'status_login.status_loginID AS 
    statusLoginID', 'status_login.description AS statusLogindesc'])
    ->leftJoin('login_profile', 'login_profile.login_profileID = supplier_profile.login_profile_ID')
    ->leftJoin('status_login', 'status_login.status_loginID = login_profile.status_login_ID')
    //->where(['=', 'status_login.description', $activeSupplier])
    ->orderBy(['supplier_profile.supplier_profileID' => SORT_ASC])
    ->asArray()
    ->all();

    $dataSend['supplierChatInfoListTable'] = $supplierChatInfoListTable;

    $this->layout = 'admin/main';
    $html= $this->renderAjax('@app/views/admin/displaychatmessage.php',$dataSend);
    echo $html;
}

But it return the 'same' supplierID for both supplier as show below:

Updated div result from displaychatmessage.php on ajax call

and browser console give me this error?(updated):-

Updated Ajax Error Message when Page Load and error after click

btw, this is the content of displaychatmessage.php (I just try to display supllierID and their name)

    <!-- DIRECT CHAT WARNING -->
      <div class="box box-warning direct-chat direct-chat-warning">
        <div class="box-header with-border">
          <h3 class="box-title">Direct Chat</h3>

          <div class="box-tools pull-right">
            <span data-toggle="tooltip" title="3 New Messages" class="badge bg-yellow">3</span>
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Contacts" data-widget="chat-pane-toggle">
              <i class="fa fa-comments"></i></button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <!-- /.box-header -->
        <div class="box-body">
          <!-- Conversations are loaded here -->
          <div class="direct-chat-messages">
            <!-- Message. Default to the left -->
            <div class="direct-chat-msg">
              <div class="direct-chat-info clearfix">
                <?php for($z = 0; $z < count($supplierChatInfoListTable); $z++){?>
                <span class="direct-chat-name pull-left">Supplier ID: <?=$supplierChatInfoListTable[$z]['supplierID']?>, <?=$supplierChatInfoListTable[$z]['supplierFirstname']?> <?=$supplierChatInfoListTable[$z]['supplierMiddlename']?> <?=$supplierChatInfoListTable[$z]['supplierLastname']?></span>
                <?php }?>
                <span class="direct-chat-timestamp pull-right">23 Jan 2:00 pm</span>
              </div>
              <!-- /.direct-chat-info -->
              <img class="direct-chat-img" src="dist/img/user1-128x128.jpg" alt="Message User Image"><!-- /.direct-chat-img -->
              <div class="direct-chat-text">
                Is this template really for free? That's unbelievable!
              </div>
              <!-- /.direct-chat-text -->
            </div>
            <!-- /.direct-chat-msg -->

            <!-- Message to the right -->
            <div class="direct-chat-msg right">
              <div class="direct-chat-info clearfix">
                <span class="direct-chat-name pull-right">Sarah Bullock</span>
                <span class="direct-chat-timestamp pull-left">23 Jan 2:05 pm</span>
              </div>
              <!-- /.direct-chat-info -->
              <img class="direct-chat-img" src="dist/img/user3-128x128.jpg" alt="Message User Image"><!-- /.direct-chat-img -->
              <div class="direct-chat-text">
                You better believe it!
              </div>
              <!-- /.direct-chat-text -->
            </div>
            <!-- /.direct-chat-msg -->
          </div>
          <!--/.direct-chat-messages-->

          <!-- Contacts are loaded here -->
          <div class="direct-chat-contacts">
            <ul class="contacts-list">
              <li>
                <a href="#">
                  <img class="contacts-list-img" src="dist/img/user1-128x128.jpg" alt="User Image">

                  <div class="contacts-list-info">
                        <span class="contacts-list-name">
                          Count Dracula
                          <small class="contacts-list-date pull-right">2/28/2015</small>
                        </span>
                    <span class="contacts-list-msg">How have you been? I was...</span>
                  </div>
                  <!-- /.contacts-list-info -->
                </a>
              </li>
              <!-- End Contact Item -->
            </ul>
            <!-- /.contatcts-list -->
          </div>
          <!-- /.direct-chat-pane -->
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
          <form action="#" method="post">
            <div class="input-group">
              <input type="text" name="message" placeholder="Type Message ..." class="form-control">
                  <span class="input-group-btn">
                    <button type="submit" class="btn btn-warning btn-flat">Send</button>
                  </span>
            </div>
          </form>
        </div>
        <!-- /.box-footer-->
      </div>
      <!--/.direct-chat -->

Can you help me with this? I don't know where it went wrong.


Solution

  • As you have mentioned you are getting same supplierID on clicking both supplier. This problem is caused because in your js code you are getting supplierID by id of the input i.e '#supplierID', and according to your html code the input elements of both of the suppliers have same value in their id attribute i.e 'supplierID', because of that every time js will get value from first input element with id attribute value 'supplierID'. So you need to make some changes in your html and js code. As there is separate edit button for each supplier so instead of using input to store supplierID value you can store it in a data attribute in the edit button. So your updated html code would become

    <?php $form = ActiveForm::begin([
     'id'=>'chatform'
    ]);?>
    <div class="box-body">
     <table id="example1" class="table table-bordered table-striped">
      <thead>
      <tr>
       <th>No</th>
       <th>Supplier</th>
       <th>Option(s)</th>
      </tr>
      </thead>
      <tbody>
    
      <?php 
      for($x = 0; $x < count($supplierChatInfoListTable); $x++){ 
        $supID = $supplierChatInfoListTable[$x]['supplierID']; ?>  
    
      <tr>
       <td>
        <?=$x+1?>
        <div class="form-group">
         <input type="hidden" name="<?='supplierID'.$supID?>" id="<?='supplierID'.$supID?>" class="form-control" 
          value="<?=$supID?>" style="width: 50px">
        </div>
       </td>
       <td >
        <h4><?=$supplierChatInfoListTable[$x]['supplierFirstname']?></h4>
       </td>
       <td>
        <button type="button" class="btn btn-primary btnchat" data-supplierID="<?=$supID?>"><i class="fa fa-edit"></i></button>
       </td>
      </tr>
    
      <?php } ?>
    
      </tbody>
      <tfoot>
      <tr>
       <th>No</th>
       <th>Supplier</th>
       <th>Option(s)</th>
      </tr>
      </tfoot>
     </table>
    </div>
    <?php ActiveForm::end();?>
    

    And then get the supplierID of clicked supplier from data attribute of button in js. So your js code would become

    <?php
    $urproudcode= Url::to(['admin/chatinfo2pass']);
    
    $this->registerJs("
     $(function(){
      $('.btnchat').click(function(){
        var supplierID = $(this).attr('data-supplierID');
        $.ajax({
          'url':'".$urproudcode."',
          'data':{supplierID:supplierID},
          'method':'POST',
          beforeSend: function (xhr) {
            $.blockUI({
              message: 'Processing...',
              css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
              }
            });
          },
          'success':function(data){
            $('.chatmessages').html('Success');
            if(data == 'false'){
              $.unblockUI();
              $('.chatmessages').html('Data False');
            }else{
              $.unblockUI();
              $('.chatmessages').html(data);
            }
          },
          error: function (xhr, ajaxOptions, thrownError) {
            $.unblockUI();
            $('.chatmessages').html('Failed');
            console.log(data);
          }
        });
       });
      });
     ");
    ?>
    

    I hope your problem will be solved.