I've this code snippet for ajax
request:
<script type="text/javascript">
$(document).ready(function() {
$('#temp').click(function() {
var username = $('#un').val();
$.ajax({
url: "inter.php",
data: 'user=' + username,
cache: false,
type: 'GET',
success: function(data, textStatus, jqXHR) {
if (! data.length === 0) {
$('#msg').append('available');
$('#sub').removeAttr('disabled');
} else {
$('#msg').append("Username not available");
$('#sub').attr('disabled', 'true');
}
}
});
});
});
</script>
and the code in inter.php
<?php
$arr = array('one', 'two', 'three');
if (in_array($_GET['user'], $arr)) {
echo "Username available";
} else {
//echo "0";
}
?>
But, every time I'm getting the message Username not available
.
Can anybody help? I'm newbie to ajax
.
EDIT
$_GET['user']
But the same problem remains.
To debug the code I'd added line:
alert(data + " " + data.length);
after
success: function(data, textStatus, jqXHR) {
and found that I'm getting the proper message from my php file.
Then I found that the problem is with my handler
if(!data.length === 0){
where !
operator is working on only data.length
whether I need it to work on whole comparison.
I'd changed it to
if(!(data.length === 0)){
and now it works.
The problem:
data: 'user=' + username,
$_GET['un']
You're not using the same parameter-name for "user name" or whatever. In the JS you're calling it "user", in PHP you're looking for "un".
You're sending ?user=someName
but looking for $_GET['un']
. Change it to $_GET['user']