Reputation: 5342
Js:
$(document).ready(function(){
$('#username').change(function(){
var username = $('#username').val();
$('#usernamemsg').html('<img src="<?php echo base_url()?>images/ajax_loader.gif"/> Checking');
$.ajax({
type: "POST",
url: "<?php echo base_url()?>user/username_validation",
dataType: "json",
data: "username="+username,
success: function(data){
if(data.valid){
$('#usernamemsg').html(data.msg);
}else{
$('#usernamemsg').html(data.msg);
}
}
});
});
});
Views:
<form id="add" method="post" action="">
<table>
<tr>
<td>Username</td>
<td><input type="text" id="username" name="username" />
<div id="usernamemsg"></div></td></tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password" /></td></tr>
<tr>
<td><input type="submit" name="add" value="OK" id="submit" /></td></tr>
</table></form>
Controller:
public function index(){
$data['title'] = 'Register';
$data['template'] = 'outside/validation/validation';
$this->load->view('templates/home_template',$data);
$add = $this->input->post('add');
if($add){
$data = array(
'username' => trim($this->input->post('username')),
'password' => trim($this->input->post('password')));
$this->data_mod->insert('user',$data);
redirect('registration/welcome');
}
}
public function username_validation(){
$user = $this->data_mod->validation('user',array('username' => $this->input->post('username')));
if($user >= 1){
$msg = array(
'valid' => false,
'msg' => 'Username is already taken');
}else{
$msg = array(
'valid' => true,
'msg' => 'Username is available');
}
echo json_encode($msg);
}
* I'm trying to learn English, so i speak not well.
When i press submit, the form does not notify the username field and it submit to server althought the code of js is working correct when i'm typing a username.
Could someone help me?
Upvotes: 0
Views: 2039
Reputation: 146191
Then try this inside your js
var username = $('#username').val();
if($.trim(username).length==0)
{
alert('Please enter user name !');
return false;
}
Just before following line
$('#usernamemsg').html('<img src="<?php echo base_url()?>images/ajax_loader.gif"/> Checking');
and also in your success
callback replace
if(data.valid){
$('#usernamemsg').html(data.msg);
}else{
$('#usernamemsg').html(data.msg);
}
with
$('#usernamemsg').html(data.msg);
Upvotes: 1