I have a ajax call on my onkeyup
event, that checks if the given email address is in the database or not. My problem is, that I can’t find a right solution to check if the ajax response is EMPTY and if yes I need to disable a button.
This is the ajax.php output:
JavaScript
x
9
1
$sql = "// the query";
2
3
$result = mysql_query($sql);
4
$num_rows = mysql_num_rows($result);
5
6
if($num_rows>0){
7
echo "<i>Yepp, this is taken</i>";
8
}
9
This is the JavaScript for the ajax call AND the button disable and enable function (ajax call only if the email address is valid):
JavaScript
1
42
42
1
function checkEmail(str){
2
3
email = document.getElementById('user-email').value
4
AtPos = email.indexOf("@")
5
StopPos = email.lastIndexOf(".")
6
7
if (AtPos == -1 || StopPos == -1) {
8
document.getElementById('button-reg').disabled=true;
9
}else{
10
if (str=="")
11
{
12
document.getElementById("txtHint").innerHTML="";
13
return;
14
}
15
if (window.XMLHttpRequest)
16
{// code for IE7+, Firefox, Chrome, Opera, Safari
17
xmlhttp=new XMLHttpRequest();
18
}
19
else
20
{// code for IE6, IE5
21
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
22
}
23
xmlhttp.onreadystatechange=function()
24
{
25
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
26
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
27
}
28
}
29
xmlhttp.open("GET","ajax.php?q="+str,true);
30
xmlhttp.send();
31
}
32
var htmlstring = document.getElementById("txtHint").innerHTML;
33
34
htmlstring = htmlstring.replace(/^s+/,'');
35
36
if(htmlstring==""){
37
document.getElementById('button-reg').disabled=false;
38
}else{
39
document.getElementById('button-reg').disabled=true;
40
}
41
}
42
As you can see I tried with whitespace elimination, but no luck… after empty response the button is still not disabled…
Can someone help me out here?
Advertisement
Answer
Use this function..
JavaScript
1
40
40
1
function checkEmail(str){
2
3
email = document.getElementById('user-email').value
4
AtPos = email.indexOf("@")
5
StopPos = email.lastIndexOf(".")
6
7
if (AtPos == -1 || StopPos == -1) {
8
document.getElementById('button-reg').disabled=true;
9
}else{
10
if (str=="")
11
{
12
document.getElementById("txtHint").innerHTML="";
13
return;
14
}
15
if (window.XMLHttpRequest)
16
{// code for IE7+, Firefox, Chrome, Opera, Safari
17
xmlhttp=new XMLHttpRequest();
18
}
19
else
20
{// code for IE6, IE5
21
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
22
}
23
xmlhttp.onreadystatechange=function()
24
{
25
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
26
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
27
28
htmlstring = xmlhttp.responseText.replace(/^s+/,'');
29
if(htmlstring==""){
30
document.getElementById('button-reg').disabled=false;
31
}else{
32
document.getElementById('button-reg').disabled=true;
33
}
34
}
35
}
36
xmlhttp.open("GET","ajax.php?q="+str,true);
37
xmlhttp.send();
38
}
39
}
40
Hope this helps..