0
我已經看過很多使用jquery ajax的表單驗證教程。我發現同樣的事情,所有的只是告訴只有成功的表單驗證。我需要找到如何在服務器端驗證失敗時顯示錯誤。換句話說,當我們提交一個沒有Ajax的表單時,表單會被重新填充錯誤信息而用戶提供的輸入是填充的。在這個方法中,我們使用了一些很棒的php函數,比如form_prep。這裏是視圖代碼。使用jquery.load在codeigniter中使用ajax驗證失敗後填充表單
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => 'login');
echo form_open(SITE_URL.'user/insertUser', $attributes);
?>
<p>
<label for="username">User Name <span class="required">*</span></label>
<input type="text" name="username" maxlength="255" value="<?php echo form_prep($this->input->post('username'));?>" />
<span id="username"><?php echo form_error('username'); ?></span><br />
</p>
<p>
<label for="first_name">First Name <span class="required">*</span></label>
<input type="text" name="first_name" maxlength="255" value="<?php echo form_prep($this->input->post('first_name'));?>" />
<span id="first_name"><?php echo form_error('first_name'); ?></span><br />
</p>
<p>
<label for="last_name">Last Name <span class="required">*</span></label>
<input type="text" name="last_name" maxlength="255" value="<?php echo form_prep($this->input->post('last_name')); ?>" />
<span id="last_name"><?php echo form_error('last_name'); ?></span><br />
</p>
<p>
<label for="password">Password <span class="required">*</span></label>
<input type="text" name="password" maxlength="255" value="<?php echo form_prep($this->input->post('password')); ?>" />
<span id = "password"><?php echo form_error('password'); ?></span><br />
</p>
<p>
<label for="email">Email <span class="required">*</span></label>
<input type="text" name="email" maxlength="255" value="<?php echo form_prep($this->input->post('email')); ?>" />
<span id = "email"><?php echo form_error('email'); ?></span><br />
</p>
<p>
<?php echo form_submit('submit', 'Submit', 'id="submit"'); ?>
</p>
<?php echo form_close(); ?>
你可以在這裏看到用於form_prep($這個 - >輸入 - >後( '用戶名')),這是安全問題有所幫助。但是,當我使用相同的表單重新填充ajax驗證失敗時,它不顯示錯誤,也沒有填充輸入框。而是加載表單,就好像這是第一次加載。 這裏是我如何使用它與Ajax。
首先在一個div我加載形式
$('#userform').load('<?php $this->load->view('user_form')?>');
現在AJAX
$(function()
{
$('#login').submit(function()
{
$.ajax(
{
type : 'POST',
data : $(this).serialize(),
url : $(this).attr('action'),
success : function(data)
{
if(data == 1)
{
// do something
}
else
{
$('#userform').load('<?php $this->load->view('user_form')?>');
}
}
});
return false;
});
});
最後我控制器
function insertUser()
{
if($this->form_validation->run() == FALSE)
{
echo 0;
}else{
echo 1;
}
}
更換
那麼你的解決方案是相當大的。我想要的完美的東西!再次感謝 –
歡迎您:) –