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:
$sql = "// the query"; $result = mysql_query($sql); $num_rows = mysql_num_rows($result); if($num_rows>0){ echo "<i>Yepp, this is taken</i>"; }
This is the JavaScript for the ajax call AND the button disable and enable function (ajax call only if the email address is valid):
function checkEmail(str){ email = document.getElementById('user-email').value AtPos = email.indexOf("@") StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { document.getElementById('button-reg').disabled=true; }else{ if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status == 200){ document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax.php?q="+str,true); xmlhttp.send(); } var htmlstring = document.getElementById("txtHint").innerHTML; htmlstring = htmlstring.replace(/^s+/,''); if(htmlstring==""){ document.getElementById('button-reg').disabled=false; }else{ document.getElementById('button-reg').disabled=true; } }
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..
function checkEmail(str){ email = document.getElementById('user-email').value AtPos = email.indexOf("@") StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { document.getElementById('button-reg').disabled=true; }else{ if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status == 200){ document.getElementById("txtHint").innerHTML=xmlhttp.responseText; htmlstring = xmlhttp.responseText.replace(/^s+/,''); if(htmlstring==""){ document.getElementById('button-reg').disabled=false; }else{ document.getElementById('button-reg').disabled=true; } } } xmlhttp.open("GET","ajax.php?q="+str,true); xmlhttp.send(); } }
Hope this helps..