I am developing a signup form. And for the 'Username check' feature on username name field I use an AJAX function.
My SIGN UP FORM: page1.php
<form id="user-form" method="post">
<input id="txtusername" name="txtusername" type="text"onblur="getResult2(this.value);">
<div id="showusername" class="help-block"></div>
<button type="submit" id="butnid" class="btn btn-success" onclick="check()" >Save User</button>
</form>
<script>
function check(){
if(getElementById('showusername').innerHTML=="Username available"){
document.getElementById("user-form").submit();
}
}
</script>
Then I use an AJAX function to pass the username entered in the textfield to page2.php, where username check is done.
My AJAX function:
// to check whether a user name already exist or not
function getResult2(uname)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//callback fn
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showusername").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","page2.php?variable="+uname,true);
// alert(xmlhttp);
xmlhttp.send();
}
This works fine & passes the value to page2.php. I want to disable the button in page1 when the value of a variable in page2 is 0.
My page2 code.
<?php
$un=$_GET["variable"];
//php code takes username from database & runs a for loop to check
//suppose $userName[$i] contains all usernames from database
// x is the number of elements in $username[] array.
for($i=0; $i<x;$i++)
{
if( $un == $userName[$i])
{
echo 'User name already exist';
$ret_var=0;
echo '<input type = "hidden" name = "subject1" id="subject1" value="' . $ret_var . '" />';
?>
<script>
// I want to disable the button in page1 if value of $ret_var is 0.
$(function(){
var txt = $('#subject1').val();
if(txt == 0){
$('#butnid').prop('disabled', true);
}
});
</script>
<?php
exit();
}
}
echo 'User name available';
?>
But the button does not get disabled. Any help or suggestions???