Tag Archive การตรวจสอบข้อมูล

Byphunsanit

jQuery Validation On AJAX form

ถ้าเราต้องการส่งค่าฟอร์มไปแบบเอแจ็กซ์ โดยก่อนส่งค่าไปให้ตรวจสอบเบื่องต้นก่อน สามารถทำได้โดยใช้เมธอด validate()

<!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>jQuery Validation : AJAX form</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/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>
<form action="login.php" id="formA" method="post">
	<div class="form-group">
		<label>User
			<input type="text" name="user" required minlength="5" maxlength="20">
		</label>
	</div>
	<div class="form-group">
		<label>Password
			<input type="password" name="password" required minlength="10" maxlength="50">
		</label>
	</div>
	<button type="submit" class="btn btn-default">Submit</button>
</form>
<script src="assets/jQuery/jquery.min.js"></script>
<script src="plus/jQuery/jquery-validation/jquery.validate.min.js"></script>
<script>
$(function()
{
	form = $('#formA');
	validation = form.validate();
	form.on('submit', function(event)
	{
		event.preventDefault();
		/* check form validation */
		if(validation.form() == true)
		{
			$.ajax({
				data: form.serialize(),
				dataType : 'json',
				success: function(data){
					$('#predictionCompaireA').html(data);
				},
				type: 'POST',
				url: 'login.php'
			});
		}
	});
});
</script>
</body>
</html>