Building Your Startup: Ajax for Meeting Times and Places

This tutorial is part of the Building Your Startup With PHP series on СodeHolder Tuts+. In this series, I’m guiding you through launching a startup from concept to reality using my Meeting Planner app as a real-life example.

Building Your Startup: Ajax for Meeting Times and Places

Moving Deeper Into Ajax

Last week, I delved deeper into Ajax to transform the meeting scheduling experience into a fully ajaxified model and eliminated the need for page refreshes. I got about halfway, focusing mostly on the straightforward elements.

In today’s tutorial, I’ll guide you through the more complex content panels that required a lot more troubleshooting, research, debugging, brainstorming, and recoding. As I said, there were moments when I thought I might have to give up on this feature until after the beta release. Follow along as I walk you through some of my personal nightmare from that week (doing better now, don’t worry).

I’m also going to show you how I used Google’s Chrome browser developer console to help me identify the broken areas—which can be especially difficult when working with Ajax between PHP and JavaScript. It’s like light at the end of the tunnel of darkness.

You’ve probably seen our beautiful Bootstrap switches to help organizers and participants share their preferences and make final choices for date times and places. Well, they’re not supposed to look like this after an Ajax update—but solving this problem turned out to be a big part of this feature update:

Building Your Startup: Ajax for Meeting Times and Places

If you haven’t tried out Meeting Planner yet, go ahead and schedule your first meeting with the new interactive capabilities. I do participate in the comment threads below, so tell me what you think! You can also reach me on Twitter @reifman. I’m especially interested if you want to suggest new features or topics for future tutorials.

As a reminder, all of the code for Meeting Planner is written in the Yii2 Framework for PHP. If you’d like to learn more about Yii2, check out our parallel series Programming With Yii2.

To begin, let’s look at adding meeting participants via Ajax.

Adding Meeting Participants

Building Your Startup: Ajax for Meeting Times and Places

The code to add participants is similar to what we covered earlier. But I do want to review slightly different code that updates the list of participants and all the buttons presenting their identities.

Previously, there was only one participant per meeting. Then, I enabled group meetings and created a list of buttons to indicate each participant:

Building Your Startup: Ajax for Meeting Times and Places

Whenever a participant is added, I refresh the entire list via Ajax.

Here’s the jQuery function addParticipant() which calls getParticipantButtons() after each new one is added:

function addParticipant(id) {
  // ajax add participant
  // adding someone from new_email
  new_email = $('#new_email').val();
  friend_id = $('#participant-email').val(); // also an email. blank before selection
  friend_email = $('#participant-email :selected').text();  // placeholder text before select
  // adding from friends
  if (new_email!='' && (friend_id !== undefined && friend_id!='')) {
      displayAlert('participantMessage','participantMessageOnlyOne');
      return false;
  } else if (new_email!='' && new_email!==undefined) {
    add_email = new_email;
  } else if (friend_id!='') {
    add_email = friend_email;
  } else {
    displayAlert('participantMessage','participantMessageNoEmail');
    return false;
  }
    $.ajax({
     url: $('#url_prefix').val()+'/participant/add',
     data: {
       id: id,
       add_email:add_email,
      },
     success: function(data) {
       // see remove below
       // to do - display acknowledgement
       // update participant buttons - id = meeting_id
       // hide panel
       $('#addParticipantPanel').addClass("hidden");
       if (data === false) {
         // show error, hide tell
         displayAlert('participantMessage','participantMessageError');
         return false;
       } else {
         // clear form
         $('#new_email').val('');
         // odd issue with resetting the combo box
         $("#participant-email:selected").removeAttr("selected");
         $("#participant-email").val('');
         $("#participant-emailundefined").val('');
        // show tell, hide error
         getParticipantButtons(id);
         displayAlert('participantMessage','participantMessageTell');
         refreshSend();
         refreshFinalize();
         return true;
      }
     }
  });
}

Here’s the getParticipantButtons() function:

function getParticipantButtons(id) {
  $.ajax({
   url: $('#url_prefix').val()+'/participant/getbuttons',
   data: {
     id: id,
    },
    type: 'GET',
   success: function(data) {
     $('#participantButtons').html(data);
   },
 });
}

It makes an Ajax call to the ParticipantController.php actionGetbuttons() method:

public function actionGetbuttons($id) {
      $m=Meeting::findOne($id);
      $participantProvider = new ActiveDataProvider([
          'query' => Participant::find()->where(['meeting_id'=>$id]),
          'sort'=> ['defaultOrder' => ['participant_type'=>SORT_DESC,'status'=>SORT_ASC]],
      ]);
      $result = $this->renderPartial('_buttons', [
          'model'=>$m,
          'participantProvider' => $participantProvider,
      ]);
      return $result;
    }

Note: Instead of ParticipantController, I like saying “ParCon” for short because it sounds likes a remote Star Trek command base—or indicates I’ve been working alone on this startup too long. I definitely spent too many late nights working on the Ajax feature.

Anyway, the above functions repopulate the panel with all of the updated participants.

Now, let’s move on to dates and times which rely on one of the commonly used Bootstrap Date Time picker widgets.

Adding Dates and Times

Building Your Startup: Ajax for Meeting Times and Places

Both dates and times and places turned out to be the most complicated features to ajaxify. It wasn’t so much the Bootstrap widget or Google Maps API used on the forms. It turned out to be the Bootstrap Switch Controllers—these weren’t designed or documented well for Ajax.

Problems With Bootstrap Switch Controllers via Ajax

Here’s an example of the broken switches after an Ajax submission adding a place:

Building Your Startup: Ajax for Meeting Times and Places

I’ll go through how I ultimately fixed this, but first, let’s look at meeting-time/panel.php:

<?php
use yiihelpersHtml;
use yiiwidgetsListView;
use yiibootstrapCollapse;
use kartikswitchinputSwitchInput;
?>
<div id="notifierTime" class="alert-info alert fade in" style="display:none;">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
<?php echo Yii::t('frontend',"We'll automatically notify the organizer when you're done making changes."); ?>
</div>
<div class="panel panel-default">
  <!-- Default panel contents -->
  <div class="panel-heading" role="tab" id="headingWhen">
    <div class="row"><div class="col-lg-10 col-md-10 col-xs-10"><h4 class="meeting-view">
      <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseWhen" aria-expanded="true" aria-controls="collapseWhen"><?= Yii::t('frontend','When') ?></a>
    </h4>
    <span class="hint-text">
      <?php if ($timeProvider->count<=1) { ?>
        <?= Yii::t('frontend','add one or more dates and times for participants to choose from') ?>
    <?php } elseif ($timeProvider->count>1) { ?>
      <?= Yii::t('frontend','are listed times okay?'); ?>
    <?php
      }
    ?>
    <?php if ($timeProvider->count>1 && ($model->isOrganizer() || $model->meetingSettings['participant_choose_date_time'])) { ?>
      <?= Yii::t('frontend','you can also choose the time') ?>
    <?php }?>
  </span></div><div class="col-lg-2 col-md-2 col-xs-2"><div style="float:right;">
    <?php
      if ($model->isOrganizer() || $model->meetingSettings->participant_add_date_time) { ?>
        <?= Html::a('', 'javascript:void(0);', ['class' => 'btn btn-primary glyphicon glyphicon-plus','title'=>'Add possible times','id'=>'buttonTime','onclick'=>'showTime();']); ?>
        <?php
      }
    ?>
      </div>
    </div>
  </div> <!-- end row -->
</div> <!-- end heading -->
  <div id="collapseWhen" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingWhen">
    <div class="panel-when">
      <div class="when-form hidden">
        <div id="timeMessage" class="alert-info alert fade in hidden">
          <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
          <span id="timeMsg1"><?= Yii::t('frontend','We'll automatically notify others when you're done making changes.')?></span>
          <span id="timeMsg2"><?= Yii::t('frontend','Please pick a date and time.')?></span>
        </div>
        <div id="addTime" class="hidden">
          <!-- hidden add time form -->
          <?= $this->render('_form', [
              'model' => $meetingTime,
          ]) ?>
        </div>
      </div>
    <table class="table" id="meeting-time-list" class="hidden">
  <?php
   if ($timeProvider->count>0):
  ?>
  <!-- Table -->
    <?= ListView::widget([
           'dataProvider' => $timeProvider,
           'itemOptions' => ['class' => 'item'],
           'layout' => '{items}',
           'itemView' => '_list',
           'viewParams' => ['timezone'=>$timezone,'timeCount'=>$timeProvider->count,'isOwner'=>$isOwner,'participant_choose_date_time'=>$model->meetingSettings['participant_choose_date_time'],'whenStatus'=>$whenStatus],
       ]) ?>
  <?php endif; ?>
  </table>
  </div>
</div>
</div>

You’ll notice the timeMessage which provides pre-loaded alerts to display under certain ajax conditions as I reviewed in the last episode. And, largely, the code begins to follow the same formats I’ve used on the other panels.

As much as possible, I tried to build on prior approaches and reuse code structure when ajaxifying each content panel.

Here’s the toggle panel JavaScript within Meeting.js:

//show the panel
function showTime() {
  if ($('#addTime').hasClass( "hidden")) {
    $('#addTime').removeClass("hidden");
    $('.when-form').removeClass("hidden");
  }else {
    $('#addTime').addClass("hidden");
    $('.when-form').addClass("hidden");
  }
};

function cancelTime() {
  $('#addTime').addClass("hidden");
  $('.when-form').addClass("hidden");
}

When the panel appears and the user submits a new date time, it calls addTime():

function addTime(id) {
    start_time = $('#meetingtime-start_time').val();
    start = $('#meetingtime-start').val();
    if (start_time =='' || start=='') {
      displayAlert('timeMessage','timeMsg2');
      return false;
    }
    // ajax submit subject and message
    $.ajax({
       url: $('#url_prefix').val()+'/meeting-time/add',
       data: {
         id: id,
        start_time: encodeURIComponent(start_time),
        start:encodeURIComponent(start),
      },
       success: function(data) {
         //$('#meeting-note').val('');
         insertTime(id);
         displayAlert('timeMessage','timeMsg1');
         return true;
       }
    });
    $('#addTime').addClass('hidden');
  }

This invokes the MeetingTimeController.php actionAdd() Ajax function:

    public function actionAdd($id,$start,$start_time) {
      Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
      $timezone = MiscHelpers::fetchUserTimezone(Yii::$app->user->getId());
      date_default_timezone_set($timezone);
      $model = new MeetingTime();
      $model->start = urldecode($start);
      $model->start_time = urldecode($start_time);
      if (empty($model->start)) {
        $model->start = Date('M d, Y',time()+3*24*3600);
      }
      $model->tz_current = $timezone;
      $model->duration = 1;
      $model->meeting_id= $id;
      $model->suggested_by= Yii::$app->user->getId();
      $model->status = MeetingTime::STATUS_SUGGESTED;
      $selected_time = date_parse($model->start_time);
      if ($selected_time['hour'] === false) {
        $selected_time['hour'] =9;
        $selected_time['minute'] =0;
      }
      // convert date time to timestamp
      $model->start = strtotime($model->start) +  $selected_time['hour']*3600+ $selected_time['minute']*60;
      $model->end = $model->start + (3600*$model->duration);
      $model->save();
      return true;
    }

It was when I began adding new date times or places via Ajax that I ran into a wall trying to reinitialize the Bootstrap Switch controller which I began using back in the earlier Scheduling Availability and Choices episode.

I’d reload the rows of date times and all of the switch controllers on the page had broken.

Part of the problem was that Ajax re-instantiation for the Bootstrap Switch wasn’t well documented. After trying a handful of things in the dark and looking for help on the interwebs, I finally found my way to this.

The $("input[name='meeting-time-choice']").map(function(){}  loops through each switch control, and the set of $(this).bootstrapSwitch(property,value) commands reset the control settings. It took some time to discover the appropriate control API.

function insertTime(id) {
    $.ajax({
     url: $('#url_prefix').val()+'/meeting-time/inserttime',
     data: {
       id: id,
      },
      type: 'GET',
     success: function(data) {
      $("#meeting-time-list").html(data).removeClass('hidden');
       $("input[name='time-chooser']").map(function(){
          //$(this).bootstrapSwitch();
          $(this).bootstrapSwitch('onText','<i class="glyphicon glyphicon-ok"></i>&nbsp;choose');
          $(this).bootstrapSwitch('offText','<i class="glyphicon glyphicon-remove"></i>');
          $(this).bootstrapSwitch('onColor','success');
          $(this).bootstrapSwitch('handleWidth',70);
          $(this).bootstrapSwitch('labelWidth',10);
          $(this).bootstrapSwitch('size','small');
        });
        $("input[name='meeting-time-choice']").map(function(){
          //$(this).bootstrapSwitch();
          $(this).bootstrapSwitch('onText','<i class="glyphicon glyphicon-thumbs-up"></i>&nbsp;yes');
          $(this).bootstrapSwitch('offText','<i class="glyphicon glyphicon-thumbs-down"></i>&nbsp;no');
          $(this).bootstrapSwitch('onColor','success');
          $(this).bootstrapSwitch('offColor','danger');
          $(this).bootstrapSwitch('handleWidth',50);
          $(this).bootstrapSwitch('labelWidth',10);
          $(this).bootstrapSwitch('size','small');
        });
     },
   });
   refreshSend();
   refreshFinalize();
  }

Basically, I had to reconfigure every property I needed for each control from scratch. That transformed the raw checkboxes above back into the richer switch controls.

Before I reached this point, I wasted a lot of time on other workarounds. Bootstrap Switch is an amazing controller and a key part of Meeting Planner’s ease of use—but ajaxifying nearly zapped me.

Moving on, adding meeting places was similar to adding dates and times, but I’d like to use this content panel to dive into troubleshooting Ajax with Google Chrome Browser Developer tools.

Adding Meeting Places

Building Your Startup: Ajax for Meeting Times and Places

As I said earlier, it can get exceedingly confusing and frustrating debugging Ajax between JavaScript and PHP. Ajax bugs are often difficult to track down.

In this case, using the Google Chrome browser’s developer console helped me break through the void.

Generally with Ajax, you just have disfunction with no indication of what went wrong.

Here’s step by step some of the visibility that Chrome exposes that I used to track down errors.

By using the Console tab, I could see failed GET requests. This is a server error trying to request to add a place to a meeting:

Building Your Startup: Ajax for Meeting Times and Places

This helped me identify the specific arguments being requested via ajax, in this case for meeting id = 186.

Looking at the Network tab also shows these calls and their arguments:

Building Your Startup: Ajax for Meeting Times and Places

When you click on the specific query, you can see five tabs; here’s the Headers tab:

Building Your Startup: Ajax for Meeting Times and Places

In this case, the Preview tab highlighted my PHP error within the MeetingPlaceController encountered by the Ajax request:

Building Your Startup: Ajax for Meeting Times and Places

You can see how helpful this becomes—especially given the wide scope of code I had to rebuild to ajaxify all of these scheduling features.

Here’s another example of the Network tab requesting places for Meeting id = 186:

Building Your Startup: Ajax for Meeting Times and Places

The Preview tab showed that the view file being requested didn’t exist or at least wasn’t where it should be:

Building Your Startup: Ajax for Meeting Times and Places

Google Chrome’s Developer console helped me a great deal in wrapping up the Ajax work.

Thank you, Google! I won’t even tease you about my genius meme today. 

What’s Next?

I hope you’ve enjoyed both these episodes on Ajax and the transformation to fast, efficient meeting scheduling and the elimination of page refreshes. Meeting scheduling is the heart and soul of Meeting Planner, so making it work great is vital.

I personally learned a lot through this process, and the changes have made a dramatic positive impact on the service.

Please try out the faster scheduling and share Meeting Planner with your friends. As usual, I’d appreciate it if you share your experience below in the comments, and I’m always interested in your suggestions. You can always reach me on Twitter @reifman directly.

I’m getting closer to launching the experiment with WeFunder based on the implementation of the SEC’s new crowdfunding rules. You can follow our profile there if you’d like. I will also write more about this in a future tutorial.

Watch for upcoming tutorials in the Building Your Startup With PHP series.

Related Links