問題 × 解決策

Ajaxを使ってカレンダーを表示する

問題

Ajaxを使ってカレンダーを表示するには?

解決策

「Ajax」のパラメータで、特定の日付の値をカレンダー表示用の外部ファイルへPOSTで渡し、その年月の値に応じた内容に切り替えます。

タブ操作とAjax処理を連動

タブ操作でAjaxを活用し、そして選択されたタブに応じてURLを操作する記述例をご紹介します。

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

DEMOはこちら

HTML

AJAX処理を行うためのボタンと、AJAXで外部ファイルから読み込んだデータを表示させるための空の要素を用意します。

  • 今回は今月のカレンダーを表示するパターンと特定の年月のカレンダーを表示するパターン(例として2021年6月を表示させます)の2パターンになります。
  • 特定の年月のカレンダーの場合はボタンに、AJAXの処理時のキーで使う用に独自属性「y」と「m」を持たせます。

今月のカレンダーを表示するパターン

<div class="ajax-box">
<p class="btns btn-type01"><a href="#">今月のカレンダーを表示</a></p>
<div class="inner-box"></div>
</div>

特定の年月のカレンダーを表示するパターン

<div class="ajax-box">
<p class="btns btn-type01"><a href="#" y="2021" m="6">2021年6月のカレンダーを表示</a></p>
<div class="inner-box"></div>
</div>

CSS

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

.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;
}

javascriptの記述例

ボタンのクリックによってAjax処理をさせてカレンダーを表示させるjavascriptの記述例は以下になります。

if($('.ajax-box').length){
$('.ajax-box .btns a').click(function(event) {
	//aリンクの動作を停止
	event.preventDefault();
	var innerbox = $(this).closest('.ajax-box').find('.inner-box');
	innerbox.html('<div class="loading-box"></div>');
	var actionkey = "calendar";
	if( $(this).attr('y') != undefined && $(this).attr('m') != undefined ){
		var y = $(this).attr('y');
		var m = $(this).attr('m');
	}else{
		 var dt = new Date();
		var y = dt.getFullYear();
		var m = ("00" + (dt.getMonth()+1)).slice(-2);
	}
	m = ("00" + m).slice(-2);
	var d = 1;
	d = ("00" + d).slice(-2);
    var date = y + m + d;
	jQuery.ajax({
		type: 'post',
		dataType:'text',
		data: {
			'action': actionkey,
			'date': date
		},
		cache: false,
		url: "calendar.php"
	}).done(function(data) {
		innerbox.html(data);
	}).error(function(XMLHttpRequest, textStatus, errorThrown) {
		alert('error!!!');
		console.log("XMLHttpRequest : " + XMLHttpRequest.status);
		console.log("textStatus     : " + textStatus);
		console.log("errorThrown    : " + errorThrown.message);
	});
});
};

ポイント!

  • クリックしたボタンのaタグに独自属性「y」と「m」が存在するかどうかを判定し、あればその値を、なければ今月の値を取得してAJAX処理時にPOSTでデータを渡します。

外部ファイルの記述例

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

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’]」で特定の年月または今月の値を取得し、それを元に処理を行います。
  • phpでのカレンダー構築の詳しい解説は過去の記事で紹介していますので、そちらをご覧ください。
    PHPで今月のカレンダーを作成する

コメント

コメントを残す

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

one × 5 =

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

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