Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loading names array from server SQL

Status
Not open for further replies.

jubalbarca

Programmer
Oct 25, 2008
12
GB
I have this AJAX-linked PHP file, which gets a username input by the user, checks if it matches the list it has, then sends back a variable to tell the program what to do next (it only offers the log in option if the name matches).
Code:
<?php
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('JAMES', 'BUBBLES', 'SUDOBAAL');
header('Content-Type: text/javascript');
if (in_array(strtoupper($name), $userNames))
  echo json_encode("1");
else if (trim($name) == '')
   echo json_encode("2");
else
   echo json_encode("3");
?>

My problem is linking tis into an SQL table of my users. I have the following table (it's not actually screwed up, but the SQL monitor program won't go fullscreen)


I need to be able to replace the UserNames array in the code with the names loaded from the SQL table (the Array already has both usernames currently in the table I know, but that's for testing purposes as well, and I'm going to write a small script to allow new users to register into the table).

Is this possible, and how can I go about it? I'm only a Javascript specialist really, this is new territory for me...

Many thanks
 
Code:
<?php
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
if (empty($name)){
 $return = 2;
} else {
 //connect to mysql here
 $sql = "Select count(*) from usertable where `name` ='%s'";
 $result = mysql_query(sprintf($sql,  mysql_real_escape_string(trim($_GET['name'])));
 if (!$result){
  $return = 3;
 } else {
   $row = mysql_fetch_array($result);
   if ($row[0] > 0){
     $return = 1;
   } else {
     $return = 3;
   }
 }
}
//output the result now
header('Content-Type: text/javascript');
echo json_encode($return);
exit;
?>
 
Many thanks, now the problems of implementation...

Code:
<?php
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
if (empty($name)){
 $return = 2;
} else {
 //connect to mysql here
 $conn = mysql_connect("localhost", "", "");
 mysql_select_db("test", $conn);
 $sql = "SELECT count(*) FROM raiders WHERE name ='%s'";
 $result = mysql_query(sprintf($sql,  mysql_real_escape_string(trim($_GET['name'])));
 if (!$result){
  $return = 3;
 } else {
   $row = mysql_fetch_array($result);
   if ($row[0] > 0){
     $return = 1;
   } else {
     $return = 3;
   }
 }
}
//output the result now
header('Content-Type: text/javascript');
echo json_encode($return);
exit;
?>
The bvesetup gies an internal server error from the Javascript. I have tried several things fiddlng wihthe settings, but no dice.

This is the JS block in question;
Code:
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////// GETTING PLAYER NAME
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// make asynchronous HTTP request using the XMLHttpRequest object 
function processnames()
{
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    // retrieve the name typed by the user on the form
    playername = encodeURIComponent(document.getElementById("myName").value);
//window.alert(playername);
    name = playername;
    // execute the quickstart.php page from the server
    xmlHttp.open("GET", "adbnames.php?name=" + playername, true);
    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponsenames;
    // make the server request
    xmlHttp.send(null);
  }
  else
    // if the connection is busy, try again after one second  
    setTimeout('processnames()', 1000);
}

// executed automatically when a message is received from the server
function handleServerResponsenames() 
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) 
  {
//  window.alert("reponse!");
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) 
    {
      // extract the XML retrieved from the server
jsonResponse = eval(xmlHttp.responseText);
//window.alert(jsonResponse);
namm = jsonResponse;
//window.alert(namm);
	if (namm == 1){
//	window.alert(namm);
	toggleLayer(commentForm);
	}
	else if (namm == 2){
	setTimeout('processnames()', 1000);
//	window.alert(namm);
	}
	else {
	setTimeout('processnames()', 1000);
//	window.alert(namm);
	}

    } 
    // a HTTP status different than 200 signals an error
    else 
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I'm getting the bottom error, with Internal Server Error being given as the problem.

Yours gratefully,

Jubal
 
don't encode the return. just echo it instead.

Code:
echo $return;

and note that we're not returning an evaluatable object, just a string/number

this is not a js forum but i would recast your script as follows:

Code:
// make asynchronous HTTP request using the XMLHttpRequest object
var xmlHttp;
var debug = true;
function processnames(){
	// proceed only if the xmlHttp object isn't busy
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		// retrieve the name typed by the user on the form
		var playername = encodeURIComponent(document.getElementById("myName").value);
		logger(playername);
		
		// execute the quickstart.php page from the server
		xmlHttp.open("GET", "adbnames.php?name=" + playername, true);
		// define the method to handle server responses
		xmlHttp.onreadystatechange = handleServerResponsenames;
		// make the server request
		xmlHttp.send(null);
	}
	else {
		// if the connection is busy, try again after one second  
		setTimeout('processnames()', 1000);
	}
}
	
	// executed automatically when a message is received from the server
function handleServerResponsenames(){
	// move forward only if the transaction has completed
	if (xmlHttp.readyState == 4) {
		logger("reponse! =" + xmlHttp.responseText);
		// status of 200 indicates the transaction completed successfully
		if (xmlHttp.status == 200) {
			namm = xmlHttp.responseText;
			switch (namm) {
				case 1:
					toggleLayer(commentForm); //[red]query is commentForm a global variable?[/red]
					break;
				case 2:
				case 3:
					setTimeout(processNames, 1000);
					break;	
				default:
					logger(namm);
					
			} //end switch
		} //end if status
	} //end if readystate
}
/**
 * helper function to display error log messages without triggering alerts
 * @param {Object} msg
 */
function logger(msg){
	if (debug) {
		if (console) {
			console.log(msg);
		}
		else {
			var n = document.createElement('div');
			with (n.style) {
				border = 'thin solid red';
				backgroundColor = 'white';
				color = 'black';
			}
			n.innerText = msg;
			document.body.appendChild(n);
		}
	}
}
 
It's still screwing up...

CommentForm is the name of a div tag, the toggle function toggles it to visible.
 
you cannot address elements like that. you are passing a variable as an argument, not the element id.

as for 'screwing up', that is not a helpful diagnosis. the code i posted should output a bunch of stuff either in the console or at the bottom of the page.
 
The toggle function, when tested with a button, works perfectly though...

I'm just getting an 'error on page' message in the Internet Explorer Status bar and nothing at all is working.
 
use firefox with firebug installed. that should tell you where the error is.
 
I'm running Apache/MySQL/PHP on my PC, it's all being done on my home system.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top