Reputation: 41
I m trying to check if a username exists or not but even if the username doesn't exists it keeps saying "Username already exists" this is my javascript code:
$.validator.addMethod("checkUsername",
function(value, element) {
var test = "";
$.ajax({
type:"GET",
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="exists")
return false;
else
return true;
}
});
},
"Username Already Exists."
);
$("#myform").validate({
rules: {
username2: {
required: true,
minlength: 6,
checkUsername:true
},
password2: {
required: true,
minlength: 6
},
email: {
required: true,
email: true
}
}
});
});
This is my controller code:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo json_encode("notexists");
}
else
{
echo json_encode("exists");
}
}
Any Ideas about this how this can be solved? Thanks in advance.
Upvotes: 0
Views: 5721
Reputation: 98728
Why are you encoding the response as JSON when you're not parsing JSON with your ajax
?
What happens when you simply do this?:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo "notexists";
}
else
{
echo "exists";
}
}
EDIT:
$.validator.addMethod("checkUsername",
function(value, element) {
var result = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(msg) {
result = (msg == "exists") ? false : true;
}
});
return result;
},
"Username Already Exists."
);
Upvotes: 4
Reputation: 49044
$.ajax
read a string. Cause you do echo json_encode
this string is json.
You can use $.getJSON
in stead of $.ajax
$.getJSON( site_url + "/ajax/checkusername/" + value, function( json ) {
if(json=="notexists"){alert('Not exists')}
});
or add $.parseJSON
to your original code:
if($.parseJSON(result)=="exists")
update: i had to change my answer
your function doesn't return the result of your $.ajax
. $.ajax
had to set your return value. Cause can't return before your ajax has been finished, you also have to add async: false
to your request (see: How do I make jQuery wait for an Ajax call to finish before it returns?)
$.validator.addMethod("checkUsername",
function(value, element) {
var test = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="notexists") {test = true; }
}
});
return test;
},
"Username Already Exists."
);
Upvotes: 2