Getting Connected with Firefox and Chrome - Calling the MySQLi API, continued
(Page 3 of 4 )
Within the JavaScript code, first we need to make certain we are responding to the correct command, so we add a global variable at the top of the source file to hold the last command issued:
var K_XUL_NAMESPACE = "http://www.mozilla.org/keymaster/
gatekeeper/there.is.only.xul";
var USER_LOGGED_IN = 0;
var lastCommand = "";
and modify the doLogin function to save the last command sent:
function doLogin(event) {
try { // try
var theArgs = new Array;
theArgs[0] = new commandArg("un",document.getElementById("userName").value);
theArgs[1] = new commandArg("pd",document.getElementById("password").value);
lastCommand = "login";
doServerRequest("login",theArgs);
} // try
catch (e) { //
alert("doLogin exception: " + e);
}//
}
When processing the server response, we use the JavaScriptsplit()function to break our comma-delimited responses into an array of name-value pairs. We then compare the value of the first entry to"true"before extracting the second returned value and setting the status text:
function retrieveServerResponse() {
if (theServerRequest.readyState == 4) { // all done
// Check return code
if (theServerRequest.status == 200) { // request terminated OK
dump("Received from server: " + theServerRequest.responseText + "\n");
//
var theResults = theServerRequest.responseText.split(",");
//
var rCode = (theResults[0].substring((theResults[0].indexOf("=")+1),
theResults[0].length)).toLowerCase();
if (lastCommand == "login") { // process login command
if (rCode == "true") { // everything OK, we know next parameter is
// session info
var lastSession = "Last login was ";
lastSession += (theResults[1].substring((theResults[1].indexOf("=")+1),
theResults[1].length)).toLowerCase();
loginOK();
setStatusText(lastSession);
} // everthing OK
else { // user NG
loginFail();
setStatusText("No user logged in");
} // user NG
} // process login command
} // request terminated OK
else { // something is wrong
alert("Response failed.");
} // something is wrong
} // all done
}
This version of the program will now log into the database, and if the username and password match (and the account is active), the welcome screen will include a status line along the bottom of the display reporting the last date and time of the user’s login:
Last login was 0000-00-00 00:00:00
All zeros appear because our initial script to create the database tables did not set an initial date in the database. Once we log in under a valid account name, the next login will yield a more welcoming message.
Next: Troubleshooting >>
More Web Standards Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Programming Firefox, written by Kenneth C. Feldt (O'Reilly, 2007; ISBN: 0596102437). Check it out today at your favorite bookstore. Buy this book now.
|
|