Advertisement
  1. Code
  2. Coding Fundamentals
  3. AJAX

Building Your Startup: Ajax for Meeting Times and Places

Scroll to top
This post is part of a series called Building Your Startup With PHP.
Building Your Startup: Security Basics
Building Your Startup: Invite People via URL
Final product imageFinal product imageFinal product image
What You'll Be Creating

This tutorial is part of the Building Your Startup With PHP series on Envato 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. Every step along the way, I'll release the Meeting Planner code as open-source examples you can learn from. I'll also address startup-related business issues as they arise.

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:

Startups Ajax - Broken Bootstrap Switch Controllers After AjaxStartups Ajax - Broken Bootstrap Switch Controllers After AjaxStartups Ajax - Broken Bootstrap Switch Controllers After Ajax

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

Startups Ajax - The Participant Panel Loaded via AjaxStartups Ajax - The Participant Panel Loaded via AjaxStartups Ajax - The Participant Panel Loaded via Ajax

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:

Startups Ajax - Refreshing Participant Button List via AjaxStartups Ajax - Refreshing Participant Button List via AjaxStartups Ajax - Refreshing Participant Button List via Ajax

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:

1
function addParticipant(id) {
2
  // ajax add participant

3
  // adding someone from new_email

4
  new_email = $('#new_email').val();
5
  friend_id = $('#participant-email').val(); // also an email. blank before selection

6
  friend_email = $('#participant-email :selected').text();  // placeholder text before select

7
  // adding from friends

8
  if (new_email!='' && (friend_id !== undefined && friend_id!='')) {
9
      displayAlert('participantMessage','participantMessageOnlyOne');
10
      return false;
11
  } else if (new_email!='' && new_email!==undefined) {
12
    add_email = new_email;
13
  } else if (friend_id!='') {
14
    add_email = friend_email;
15
  } else {
16
    displayAlert('participantMessage','participantMessageNoEmail');
17
    return false;
18
  }
19
    $.ajax({
20
     url: $('#url_prefix').val()+'/participant/add',
21
     data: {
22
       id: id,
23
       add_email:add_email,
24
      },
25
     success: function(data) {
26
       // see remove below

27
       // to do - display acknowledgement

28
       // update participant buttons - id = meeting_id

29
       // hide panel

30
       $('#addParticipantPanel').addClass("hidden");
31
       if (data === false) {
32
         // show error, hide tell

33
         displayAlert('participantMessage','participantMessageError');
34
         return false;
35
       } else {
36
         // clear form

37
         $('#new_email').val('');
38
         // odd issue with resetting the combo box

39
         $("#participant-email:selected").removeAttr("selected");
40
         $("#participant-email").val('');
41
         $("#participant-emailundefined").val('');
42
        // show tell, hide error

43
         getParticipantButtons(id);
44
         displayAlert('participantMessage','participantMessageTell');
45
         refreshSend();
46
         refreshFinalize();
47
         return true;
48
      }
49
     }
50
  });
51
}

Here's the getParticipantButtons() function:

1
function getParticipantButtons(id) {
2
  $.ajax({
3
   url: $('#url_prefix').val()+'/participant/getbuttons',
4
   data: {
5
     id: id,
6
    },
7
    type: 'GET',
8
   success: function(data) {
9
     $('#participantButtons').html(data);
10
   },
11
 });
12
}

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

1
public function actionGetbuttons($id) {
2
      $m=Meeting::findOne($id);
3
      $participantProvider = new ActiveDataProvider([
4
          'query' => Participant::find()->where(['meeting_id'=>$id]),
5
          'sort'=> ['defaultOrder' => ['participant_type'=>SORT_DESC,'status'=>SORT_ASC]],
6
      ]);
7
      $result = $this->renderPartial('_buttons', [
8
          'model'=>$m,
9
          'participantProvider' => $participantProvider,
10
      ]);
11
      return $result;
12
    }

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

Startups Ajax - The Date Time Panel Loaded via AjaxStartups Ajax - The Date Time Panel Loaded via AjaxStartups Ajax - The Date Time Panel Loaded via Ajax

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:

Startups Ajax - Bootstrap Switches for Places Broken CheckboxesStartups Ajax - Bootstrap Switches for Places Broken CheckboxesStartups Ajax - Bootstrap Switches for Places Broken Checkboxes

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

1
<?php
2
use yii\helpers\Html;
3
use yii\widgets\ListView;
4
use yii\bootstrap\Collapse;
5
use \kartik\switchinput\SwitchInput;
6
?>
7
<div id="notifierTime" class="alert-info alert fade in" style="display:none;">
8
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
9
<?php echo Yii::t('frontend',"We'll automatically notify the organizer when you're done making changes."); ?>
10
</div>
11
<div class="panel panel-default">
12
  <!-- Default panel contents -->
13
  <div class="panel-heading" role="tab" id="headingWhen">
14
    <div class="row"><div class="col-lg-10 col-md-10 col-xs-10"><h4 class="meeting-view">
15
      <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseWhen" aria-expanded="true" aria-controls="collapseWhen"><?= Yii::t('frontend','When') ?></a>
16
    </h4>
17
    <span class="hint-text">
18
      <?php if ($timeProvider->count<=1) { ?>
19
        <?= Yii::t('frontend','add one or more dates and times for participants to choose from') ?>
20
    <?php } elseif ($timeProvider->count>1) { ?>
21
      <?= Yii::t('frontend','are listed times okay?'); ?>
22
    <?php
23
      }
24
    ?>
25
    <?php if ($timeProvider->count>1 && ($model->isOrganizer() || $model->meetingSettings['participant_choose_date_time'])) { ?>
26
      <?= Yii::t('frontend','you can also choose the time') ?>
27
    <?php }?>
28
  </span></div><div class="col-lg-2 col-md-2 col-xs-2"><div style="float:right;">
29
    <?php
30
      if ($model->isOrganizer() || $model->meetingSettings->participant_add_date_time) { ?>
31
        <?= Html::a('', 'javascript:void(0);', ['class' => 'btn btn-primary glyphicon glyphicon-plus','title'=>'Add possible times','id'=>'buttonTime','onclick'=>'showTime();']); ?>
32
        <?php
33
      }
34
    ?>
35
      </div>
36
    </div>
37
  </div> <!-- end row -->
38
</div> <!-- end heading -->
39
  <div id="collapseWhen" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingWhen">
40
    <div class="panel-when">
41
      <div class="when-form hidden">
42
        <div id="timeMessage" class="alert-info alert fade in hidden">
43
          <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
44
          <span id="timeMsg1"><?= Yii::t('frontend','We\'ll automatically notify others when you\'re done making changes.')?></span>
45
          <span id="timeMsg2"><?= Yii::t('frontend','Please pick a date and time.')?></span>
46
        </div>
47
        <div id="addTime" class="hidden">
48
          <!-- hidden add time form -->
49
          <?= $this->render('_form', [
50
              'model' => $meetingTime,
51
          ]) ?>
52
        </div>
53
      </div>
54
    <table class="table" id="meeting-time-list" class="hidden">
55
  <?php
56
   if ($timeProvider->count>0):
57
  ?>
58
  <!-- Table -->
59
    <?= ListView::widget([
60
           'dataProvider' => $timeProvider,
61
           'itemOptions' => ['class' => 'item'],
62
           'layout' => '{items}',
63
           'itemView' => '_list',
64
           'viewParams' => ['timezone'=>$timezone,'timeCount'=>$timeProvider->count,'isOwner'=>$isOwner,'participant_choose_date_time'=>$model->meetingSettings['participant_choose_date_time'],'whenStatus'=>$whenStatus],
65
       ]) ?>
66
  <?php endif; ?>
67
  </table>
68
  </div>
69
</div>
70
</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:

1
//show the panel

2
function showTime() {
3
  if ($('#addTime').hasClass( "hidden")) {
4
    $('#addTime').removeClass("hidden");
5
    $('.when-form').removeClass("hidden");
6
  }else {
7
    $('#addTime').addClass("hidden");
8
    $('.when-form').addClass("hidden");
9
  }
10
};
11
12
function cancelTime() {
13
  $('#addTime').addClass("hidden");
14
  $('.when-form').addClass("hidden");
15
}

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

1
function addTime(id) {
2
    start_time = $('#meetingtime-start_time').val();
3
    start = $('#meetingtime-start').val();
4
    if (start_time =='' || start=='') {
5
      displayAlert('timeMessage','timeMsg2');
6
      return false;
7
    }
8
    // ajax submit subject and message

9
    $.ajax({
10
       url: $('#url_prefix').val()+'/meeting-time/add',
11
       data: {
12
         id: id,
13
        start_time: encodeURIComponent(start_time),
14
        start:encodeURIComponent(start),
15
      },
16
       success: function(data) {
17
         //$('#meeting-note').val('');

18
         insertTime(id);
19
         displayAlert('timeMessage','timeMsg1');
20
         return true;
21
       }
22
    });
23
    $('#addTime').addClass('hidden');
24
  }

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

1
    public function actionAdd($id,$start,$start_time) {
2
      Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
3
      $timezone = MiscHelpers::fetchUserTimezone(Yii::$app->user->getId());
4
      date_default_timezone_set($timezone);
5
      $model = new MeetingTime();
6
      $model->start = urldecode($start);
7
      $model->start_time = urldecode($start_time);
8
      if (empty($model->start)) {
9
        $model->start = Date('M d, Y',time()+3*24*3600);
10
      }
11
      $model->tz_current = $timezone;
12
      $model->duration = 1;
13
      $model->meeting_id= $id;
14
      $model->suggested_by= Yii::$app->user->getId();
15
      $model->status = MeetingTime::STATUS_SUGGESTED;
16
      $selected_time = date_parse($model->start_time);
17
      if ($selected_time['hour'] === false) {
18
        $selected_time['hour'] =9;
19
        $selected_time['minute'] =0;
20
      }
21
      // convert date time to timestamp

22
      $model->start = strtotime($model->start) +  $selected_time['hour']*3600+ $selected_time['minute']*60;
23
      $model->end = $model->start + (3600*$model->duration);
24
      $model->save();
25
      return true;
26
    }

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.

1
function insertTime(id) {
2
    $.ajax({
3
     url: $('#url_prefix').val()+'/meeting-time/inserttime',
4
     data: {
5
       id: id,
6
      },
7
      type: 'GET',
8
     success: function(data) {
9
      $("#meeting-time-list").html(data).removeClass('hidden');
10
       $("input[name='time-chooser']").map(function(){
11
          //$(this).bootstrapSwitch();

12
          $(this).bootstrapSwitch('onText','<i class="glyphicon glyphicon-ok"></i>&nbsp;choose');
13
          $(this).bootstrapSwitch('offText','<i class="glyphicon glyphicon-remove"></i>');
14
          $(this).bootstrapSwitch('onColor','success');
15
          $(this).bootstrapSwitch('handleWidth',70);
16
          $(this).bootstrapSwitch('labelWidth',10);
17
          $(this).bootstrapSwitch('size','small');
18
        });
19
        $("input[name='meeting-time-choice']").map(function(){
20
          //$(this).bootstrapSwitch();

21
          $(this).bootstrapSwitch('onText','<i class="glyphicon glyphicon-thumbs-up"></i>&nbsp;yes');
22
          $(this).bootstrapSwitch('offText','<i class="glyphicon glyphicon-thumbs-down"></i>&nbsp;no');
23
          $(this).bootstrapSwitch('onColor','success');
24
          $(this).bootstrapSwitch('offColor','danger');
25
          $(this).bootstrapSwitch('handleWidth',50);
26
          $(this).bootstrapSwitch('labelWidth',10);
27
          $(this).bootstrapSwitch('size','small');
28
        });
29
     },
30
   });
31
   refreshSend();
32
   refreshFinalize();
33
  }

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

Startups Ajax - The Meeting Places Panel Loaded via AjaxStartups Ajax - The Meeting Places Panel Loaded via AjaxStartups Ajax - The Meeting Places Panel Loaded via Ajax

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:

Startups Ajax - Google Chrome Browser Console TabStartups Ajax - Google Chrome Browser Console TabStartups Ajax - Google Chrome Browser Console Tab

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:

Startups Ajax - Google Chrome Browser Network TabStartups Ajax - Google Chrome Browser Network TabStartups Ajax - Google Chrome Browser Network Tab

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

Startups Ajax - Google Chrome Browser Headers TabStartups Ajax - Google Chrome Browser Headers TabStartups Ajax - Google Chrome Browser Headers Tab

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

Startups Ajax - Google Chrome Browser Preview TabStartups Ajax - Google Chrome Browser Preview TabStartups Ajax - Google Chrome Browser Preview Tab

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:

Startups Ajax - Google Chrome Browser Network TabStartups Ajax - Google Chrome Browser Network TabStartups Ajax - Google Chrome Browser Network Tab

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

Startups Ajax - Google Chrome Browser Preview TabStartups Ajax - Google Chrome Browser Preview TabStartups Ajax - Google Chrome Browser Preview Tab

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

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.