หมวดหมู่: jQuery

alert message จาก ajaxalert message จาก ajax

ส่วนติดต่อกับผู้ใช้ บางครั้งเราต้องตรวจสอบเงื่อนไขในหลายจุด ถ้าเจอแล้วส่ง message เป็น notification ต่าง ๆ ตาม contextual ต่าง ๆ ถ้ามีทั้งการแจ้งเตือน ทั้ง แจ้ง error ความผิดพลาด หลายจุด หลายเงื่อนไข ถ้าเราจะ redirect กลับไปกลับมาเพื่อแจ้ง user ก็ไม่สะดวก ทั้งที่ต้องกรอกข้อมูลใหม่ และความรู้สึกที่ว่า ทำไมไม่บอกมาซะให้หมดที่เดียว

ส่วนที่เป็น PHP เราก็เก็บ message ต่าง ๆ ไว้ใน array แล้วส่ง json กลับมาแล้วให้ function notification ใส่ bar แจ้งเตือน user message แต่ละประเภทอาจจะมีหลายข้อความ เราก็ใช้เป็น multidimensional array

<?php
$output['messages']['success'][] = 'Success! Well done its submitted.';
$output['messages']['info'][] = 'Info! take this info 1.';
$output['messages']['info'][] = 'Info! take this info 2.';
$output['messages']['warning'][] = 'Warning ! Dont submit this.';
$output['messages']['danger'] = 'Error ! Change few things.';

header ('Content-Type: application/json; charset=utf-8') ;
echo json_encode ($output) ;

ในฝั่ง ui ผมใช้แถบแจ้งเตือนของ bootsrtapt เป็นตัวอย่าง ถ้าใช้ framework อื่นก็แก้ code ด้วยครับ เวลาใช้จริงอย่าลืมแยกฟังก์ชั่น notification ไปไว้ในไฟล์ javascript ส่วนกลาง จะได้เรียกใช้ได้จากทุกหน้า

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap notification bar</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
 <script src="http://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
 <script src="http://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>alert under here</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below) , or include individual files as needed -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
function notifications (notifications) {
	html = '';
	$.each (notifications, function (type, messages) {
		if ($.isArray (messages)) {
			if (messages.length == 1) {
				html += '<div class="alert alert-'+type+'">'+messages[0]+'</div>';
			}
			else
			{
				html += '<div class="alert alert-'+type+'"><ul>';
				$.each (messages, function (ordered, message) {
					html += '<li>'+message+'</li>';
				}) ;
				html += '</ul></div>';
			}
		}
		else
		{
			html += '<div class="alert alert-'+type+'">'+messages+'</div>';
		}
	}) ;
	$ ('h1:eq (0) ') .after (html) ;
}

$ (function () {
	$.ajax ({
		dataType:'json',
		success : function (datas) {
			notifications (datas.messages) ;
		},
		url : 'alert.php'
	}) ;
}) ;
</script>
</body>
</html>