I've always been hesitant to learn JS since I have to go out of my way to debug the script. The support for such things is poor compared to IDEs for C#/C++ etc.
I'm trying a simple PHP and JS script to retrieve data from my MySQL database, but "onchange" doesn't seem to be triggered:
<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript'>
function ShowUser(name)
{
if(name == "")
{
document.getElementById("display").innerHTML = "Please enter a username to check";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "index.php?uName=" + name, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php
$data = array();
if(!empty($_GET['uName']))
{
$r = mysql_connect("localhost", "root", "pass") or die("Couldn't connect to db");
mysql_select_db("db", $r) or die ("Couldn't select db");
$q = mysql_query("select * from users where uName = '{$_GET['uName']}'") or die("Couldn't query table");
$data = mysql_fetch_assoc($q);
mysql_close($r);
}
?>
<input type="text" name="fUName" onchange="ShowUser(this.value);" style="width:125px;">
</form>
<div id="display"><?php print_r($data); ?></div>
</body>
</html>
It must be something silly I'm missing. Most of this code was taken from W3schools and put with my own PHP and HTML.
Thanks for any help.
varto avoid polluting the global scope. I'd avoid line-breaks after parentheses in JavaScript, since it can lead to bugs. Try this for example:var abc = function () { } (0 === 1);. (With the line-break afterfunction ().)