getting an unexpected behavior when calling a php function from javascript
i'm using ajax to call a php function from javascript, but i got confused
with the results, i have this on my php functions file :
<?php
if(isset($_GET['function']) && isset($_GET['value']) ){
if($_GET['function'] == "hey"){
echo user_exists($_GET['value']) ? "true": "false";
}
}
function user_exists($username){
$username = sanitize($username);
$query = mysql_query("SELECT COUNT('user_id') FROM users WHERE
username = '$username'");
return (mysql_result($query, 0) == 1) ? true : false;
}
and on my registration file, where i'm writing my javascript :
<script>
//some code here
var x;
the_user_exist(element.value);
//element is just a variable containing the getElementById... stuff
console.log(x);
if( x == "true" ){
document.getElementById('err'+id).innerHTML ="<img
src=\"css/images/cross.png\"></img>";
fields_state[ctrl] = 0;
}else {
document.getElementById('err'+id).innerHTML ="<img
src=\"css/images/tick.png\"></img>";
fields_state[ctrl] = 1;
}
//ajax funct
function the_user_exist(str){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
console.log('1');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log('3');
x = xmlhttp.responseText;
}
}
xmlhttp.open("GET","core/functions/users.php?function=hey&value="+str,true);
xmlhttp.send();
console.log('2');
}
//some code here
</script>
if you follow the console.log(1) ,2 and 3 and x, the result of logging on
chrome was: 1 2 undefined 3 true like if javascript tests are running
before the ajax work is finished, when i changed the true to false in :
xmlhttp.open("GET","core/functions/users.php?function=hey&value="+str,false);
it worked fine in Chrome not in Firefox,
i need some explanation of what is wrong with what i am doing more than
giving me a code.
No comments:
Post a Comment