問題 × 解決策

Ajaxを使ってタブ操作でカレンダーを表示する

問題

Ajaxを使ってタブ操作でカレンダーを表示するには?

解決策

  • 今月の値を「Ym」形式で取得し、今月から任意の数の未来の月をタブとして生成します。
  • アクティブになったタブの値(年月の値)を「Ajax」のパラメータで、カレンダー表示用の外部ファイルへPOSTで渡し、その年月の値に応じた内容に切り替えます。

 

タブ操作とAjax処理を連動してカレンダーを表示

タブ操作でAjaxを活用し、そして選択されたタブに応じてカレンダーを表示する記述例をご紹介します。

今回は以下の以下の3つの記事を応用していますので、ぜひこちらもご覧ください。

DEMOはこちら

  • タブを切り替える度に表示されるカレンダーが切り替わります。

HTML

AJAXで外部ファイルから読み込んだデータを表示させるための空の要素を用意します。
タブは独自属性をjavascriptを介して設定したいため、javascriptで後ほど生成します。

<div class="ajax-box">
<div class="inner-box"></div>
</div>

CSS

タブを横並びにするためと、AJAXの処理が完了するまで、ロード中であることを示すため、ローディング画像を表示させるためのcss設定を行います。

.tab-list{
	margin-bottom: 15px;
	letter-spacing: -.4em;
}
.tab-list > li{
	display: inline-block;
	vertical-align: middle;
	width: 18%;
	margin: 0 1%;
	letter-spacing: normal;
}
.tab-list > li:first-child{
	margin-left: 0;
}
.tab-list > li:last-child{
	margin-right: 0;
}
.tab-list > li a{
	display: block;
	padding: 10px;
	color: #ffffff;
	text-decoration: none;
	text-align: center;
	background-color: #F15A24;
	border: 1px solid #F15A24;
}
.tab-list > li a:hover,
.tab-list > li.on a{
	color: #F15A24;
	background-color: #ffffff;
}
.ajax-box .inner-box .loading-box{
	display: block;
	height: 130px;
	background-image: url("ajax-loader.gif");
	background-position: center center;
	background-repeat: no-repeat;
	background-size: 100px auto;
}

今月から5ヶ月分のタブを生成する

今月から5ヶ月分のタブを生成する記述例は以下になります。

$('.ajax-box').prepend('<ul class="tab-list"></ul>');
var current_date = new Date();
var current_y = current_date.getFullYear();
var current_m = current_date.getMonth();
var d = 1;
var dp_d = ("00" + d).slice(-2);
for( var i = 0; i <= 4; i++ ){
    var tabMonth = new Date(current_y, current_m + i);
    var dp_y = tabMonth.getFullYear();
    var dp_m = ("00" + (tabMonth.getMonth()+1)).slice(-2);
    var dp_ymd = dp_y + dp_m + dp_d;
    var dp_ym_label = dp_y + '年' + '<br>' + dp_m + '月';
    $('.ajax-box .tab-list').append('<li class="'+dp_ymd+'" date="'+dp_ymd+'"><a href="#">'+dp_ym_label+'</a></li>');
}
  • まず「prepend」でulタグを生成します。
  • 「new Date()」から年を「getFullYear()」、月を「getMonth()」で取得します。
  • 日は1を設定し、「(“00” + 日の値).slice(-2)」で0埋めしておきます。
  • for文で変数iを0から4まで5回、繰り返します。
  • 【繰り返し処理内】「new Date(current_y, current_m + i)」で今月から月の値に変数iをプラスして、再び年、月の値を取り出します。
  • 【繰り返し処理内】取り出した月の値を0埋めして、文字列として年、月、日(先ほどの1日としての値)を連結させます。
  • 【繰り返し処理内】そして「append」でliタグを生成します。
    生成する際に、先ほど連結させた値を独自属性「date」として設定します。

ポイント!

new Date(current_y, current_m + 任意の数値)」で来月、再来月等の値を取得することができます。

タブ操作でAjax処理を行い、指定した月のカレンダーを表示する記述例

タブ操作でAjax処理を行い、指定した月のカレンダーを表示する記述例は以下になります。

if($('.ajax-box').length){
	// AJAX用関数
	function tabajax( date, actionkey ){
		jQuery.ajax({
			type: 'post',
			dataType:'text',
			cache: false,
			data: {
				'action': actionkey,
				'date': date
			},
			url: "calendar.php"
		}).done(function(data) {
			$('.ajax-box .inner-box').html(data);
			if(document.location.href.indexOf('?') > -1) {
				var url = document.location.href.substring(window.location.href.lastIndexOf('/') + 1).split('?');
				var url = url[0]+"?date="+date;
			}else{
				var url = document.location.href.substring(window.location.href.lastIndexOf('/') + 1).split('?');
				var url = url[0]+"?date="+date;
			}
			history.pushState(null,null,url);
		}).error(function(XMLHttpRequest, textStatus, errorThrown) {
			alert('error!!!');
			console.log("XMLHttpRequest : " + XMLHttpRequest.status);
			console.log("textStatus     : " + textStatus);
			console.log("errorThrown    : " + errorThrown.message);
		});
	} // tabajax
	// 初期読み込み時
	$('.ajax-box .inner-box').html('<div class="loading-box"></div>');
	if(location.search.match(/date=(.*?)(&|$)/)){
		var date = location.search.match(/date=(.*?)(&|$)/)[1];
	}else{
		var date = $('.ajax-box .tab-list > li').eq(0).attr('date');
	}
	$('.ajax-box .tab-list > li').removeClass('on');
	$('.ajax-box .tab-list > li').each( function(){
		if( $(this).attr('date') == date ){
			$(this).addClass('on');
		}
	});
	var actionkey = "calendar";
	tabajax( date, actionkey ); // AJAXの実行
	// タブのクリック時
	$('.ajax-box .tab-list > li a').click(function(event) {
		//aリンクの動作を停止
		event.preventDefault();
		$('.ajax-box .tab-list > li').removeClass('on');
		$(this).closest('li').addClass('on');
		$('.ajax-box .inner-box').html('<div class="loading-box"></div>');
		var date = $(this).closest('li').attr("date");
		tabajax( date, actionkey ); // AJAXの実行
	});
};

ポイント!

  • AJAX処理をユーザー定義関数に収めて、引数としてタブのキー(日付の値)とアクションキーを設定します。
  • ページの読み込み時とタブのクリック時に先ほどのAJAX処理を詰め込んだユーザー定義関数を実行します。

外部ファイルの記述例

外部ファイルの記述例は以下になります。

calendar.php

<?php
function calendar(){
	date_default_timezone_set('Asia/Tokyo');
	include(dirname(__FILE__)."/../pahooCalendar.php");
	//pahooCalendarクラス
	$pcl = new pahooCalendar();
	$pcl->setLanguage('jp');
	if(!empty($_POST['date'])):
	$date = $_POST['date'] ;
	else:
	$date = date();
	endif;
	// 年月を取得する
	$ym_now = date( "Ym", strtotime($date) );
	$ym_label = date( "Y年m月", strtotime($date) );
	$y = substr($ym_now, 0, 4);
	$m = substr($ym_now, 4, 2);
	?>
	<h3 class="title-level03"><?php echo $ym_label; ?></h3>
	<table class="type03 section-sss small sp-t100p">
		<thead>
	<tr>
		<th scope="col"><span class="not">日</span></th>
		<th scope="col"><span class="not">月</span></th>
		<th scope="col"><span class="not">火</span></th>
		<th scope="col"><span class="not">水</span></th>
		<th scope="col"><span class="not">木</span></th>
		<th scope="col"><span class="not">金</span></th>
		<th scope="col"><span class="not">土</span></th>
	</tr>
		</thead>
		<tbody>
	<tr>
	<?php
	// 1日の曜日を取得
	$wd1 = date("w", mktime(0, 0, 0, $m, 1, $y));
	// その数だけ空白を表示
	for ($i = 1; $i <= $wd1; $i++) {
		echo "<td> </td>";
	}
	// 1日から月末日までの表示
	$d = 1;
	while (checkdate($m, $d, $y)) {
		$date_d = sprintf('%02d', $d);
		$cal_text = $d;
		if($pcl->isHoliday($y,$m,$date_d)){
			echo '<td class="close holiday">'.$cal_text.'</td>';
			if(date("w", strtotime(date($y.$m.$date_d))) == 6){
				echo "</tr>";
				// 次の週がある場合は新たな行を準備
				if (checkdate($m, $d + 1, $y)) {
					echo "<tr>";
				}
			}
		}elseif(date("w", strtotime(date($y.$m.$date_d))) == 6){
			// 今日が土曜日の場合、週(行)を終了
			echo '<td class="sat">'.$cal_text.'</td>';
			echo "</tr>";
			// 次の週がある場合は新たな行を準備
			if (checkdate($m, $d + 1, $y)) {
				echo "<tr>";
			}
		}elseif(date("w", strtotime(date($y.$m.$date_d))) == 0){
			// 今日が日曜日の場合
			echo '<td class="sun">'.$cal_text.'</td>';
		}else{
			echo '<td>'.$cal_text.'</td>';
		}
		$d++;
	}
	// 最後の週の土曜日まで移動
	$wdx = date("w", mktime(0, 0, 0, $m + 1, 0, $y));
	for ($i = 1; $i < 7 - $wdx; $i++) {
		echo '<td><span class="not">&nbsp;</span></td>';
	}
	?>
	</tr>
		</tbody>
	</table>
<?php
} //calendar
if(!empty($_POST['action'])):
$actions = $_POST['action'];
$actions();
endif;
?>

ポイント!

  • $_POST[‘date’]」でタブのキーの値を取得し、それを元に処理を行います。

コメント

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

8 − three =

「問題 × 解決策」
月別アーカイブ一覧

「問題 × 解決策」
月別アーカイブ一覧