我正在使用codeigniter和AJAX使用jQuery创建一个登录表单。我的问题是如何显示从codeigniter返回的验证错误。如果用户正确登录,一切正常,但我在codeigniter中使用验证工具,如果登录失败,我想在页面上显示这些错误。如何将验证错误从控制器传递回ajax函数calll的.success?我的代码在下面..谢谢!
登录视图
<script type="text/javascript">
$('#login_form').submit(function(e) {
var username = $('#username').val();
var password = $('#password').val();
var loginData = "&username=" + username + "&password=" + password;
$.ajax({
type: "POST",
url: "<?php echo site_url('login/validate') ?>",
data: loginData,
success: function(data) {
//My question is how to dislpay data if validation_errors() has something and do nothing if login properly worked.
}
});
});
</scirpt>
<form id="login_form">
Username: <input type="text" name="username" id="username" size="15" /><br />
Password: <input type="password" name="passwort" id="password" size="15" /><br />
<div align="center">
<p><input type="submit" value="Login" /></p>
</div>
</form>
登录控制器
function validate() {
foreach($_POST as $key => $value ) {
$$key = trime(value);
}
$query = ..... call the model to validate in DB this works and will return true or false if it authenticates...
if( $query ) {
//redirect to the loggedin view..
rediect('site/loggedin');
}
else {
//here I want to pass back the validation errors to be shown on the current view.
}
}
答案 0 :(得分:2)
jondavidjohn就在眼前。但是,要获得验证,您需要通过ajax:
返回validation_errors()您需要在某处放置验证错误:
HTML
<div class="errors"></div>
JQUERY
$.ajax({
type: "POST",
url: "<?php echo site_url('login/validate') ?>",
data: loginData,
success: function(data) {
if (data == undefined) {
window.location = "<?php echo site_url('controller/loggedin') ?>"; //javascript redirect by jondavidjohn
}
else {
$('.errors').html(data); //how you get and set the errors to the html file
}
}
});
PHP
function login() {
if ($this->form_validation->run() != TRUE) {
echo validation_errors(); // this returns the errors via ajax
}
}
答案 1 :(得分:0)
您必须通过javascript处理重定向,因此在ajax成功处理程序
中$.ajax({
type: "POST",
url: "<?php echo site_url('login/validate') ?>",
data: loginData,
success: function(data) {
if (data) { //if the data returned is true (or 1)
window.location = "<?php echo site_url('controller/loggedin') ?>"; //javascript redirect
}
else { //if the data returned is not true (or 0)
//show your error here
}
}
});
并且在您的控制器中,您只需回显1
或0
,具体取决于登录的成功与否。如果$query
是布尔值true / false,则只需回显它。
function validate() {
foreach($_POST as $key => $value ) {
$$key = trime(value);
}
$query = ..... call the model to validate in DB this works and will return true or false if it authenticates...
echo $query; //should be true/false which will be interpreted by the ajax success callback.
}