Loading
Showing posts with label ajax and php. Show all posts
Showing posts with label ajax and php. Show all posts

Thursday, April 23, 2009

Ajax lookup function

Here is a simple look up function using ajax (XMLHttpRequest object).

function lookup(tbl,res,fld,val) {
var req;
var url='lookup.php?tbl='+tbl+'&res='+res+'&fld='+fld+'&val='+val;
req = false;
// branch for native XMLHttpRequest object

if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
//req.onreadystatechange = processReqChange;
req.open("GET", url, false);
req.send('-');
}
return req.responseText;
}

Sunday, February 10, 2008

Auto-Completing Properly

Now that you have a means to connect to a database, you can start replacing and upgrading some of the placeholder code you used in the previous chapter’s examples. Rather than using static arrays to house information on names within the database, you can get an up-to-date listing of all names in the database on the fly by merely including your database connection script (containing the PHP code to connect to the database) and performing a query to scour the user table for all name instances. Two files are in need of some dire code replacement, autocomp.php and validator.php.

<?php
//autocomp.php
//Add in our database connector.
require_once ("dbconnector.php");
//And open a database connection.
$db = opendatabase();
$foundarr = array ();
//Set up the dynamic query string.
$querystr = "SELECT name FROM user WHERE name LIKE ➥
LOWER('%" . mysql_real_escape_string ($_GET['sstring']) . "%') ORDER BY name ASC";
if ($userquery = mysql_query ($querystr)){
while ($userdata = mysql_fetch_array ($userquery)){
if (!get_magic_quotes_gpc()){
$foundarr[] = stripslashes ($userdata['name']);
} else {
$foundarr[] = $userdata['name'];
}
}
} else {
echo mysql_error();
}
//If we have any matches, then we can go through and display them.
if (count ($foundarr) > 0){
?>
<div style="background: #CCCCCC; border-style: solid; border-width: 1px;➥
border-color: #000000;">
<?php
for ($i = 0; $i < count ($foundarr); $i++){
?><div style="padding: 4px; height: 14px;" onmouseover=➥
"this.style.background = '#EEEEEE'" onmouseout=➥
"this.style.background = '#CCCCCC'" onclick=➥
"setvalue ('<?php echo $foundarr[$i]; ?>')"><?php echo $foundarr[$i]; ?></div><?php
}
?>
</div>
<?php
}
?>

Notice how the preceding code affects your autocomp.php file. Now, rather than referencing an array to check for name matches, the system actually checks within the database for any matches, using the LIKE operator. This works far better by allowing the system to check dynamically for any new names that may be in the database.
Similarly, your validator.php file now does much the same validation checking as your autocomp.php file. This time, however, rather than checking for an exact match against an array of names, the system now checks for an actual database match for the name in question. Again, this is far superior, as you now have a means to properly store information on saved names. Note that the code flow is largely the same, but now it is done properly via a real data storage model, and the result is a nicely validated form

<?php
//validator.php
//Add in our database connector.
require_once ("dbconnector.php");
//And open a database connection.
$db = opendatabase();
//Set up the dynamic query string.
$querystr = "SELECT userid FROM user WHERE name = ➥
LOWER('" . mysql_real_escape_string ( $_GET['sstring']) . "')";
if ($userquery = mysql_query ($querystr)){
if (mysql_num_rows ($userquery) == 0){
//Then return with an error.
?><span style="color: #FF0000;">Name not found...</span>>?php
} else {
//At this point we would go to the processing script.
?><span style="color: #FF0000;">Form would now submit...</span><?php
}
} else {
echo mysql_error();
}
?>




Connecting to MySQL

In order to access and make use of a MySQL database, you first must create a database and then create and manage a set of tables within that database. In order to connect to your database, however, you must also create a user that has permissions to access the database in question, and assign them a password. For the following examples, I have created a database called taskdb. I have also assigned a user called apressauth to the database and given the user a password: tasks. In order to perform this sort of database management, you can go ahead and use the command line interface MySQL provides, or try a more robust solution. I prefer phpMyAdmin (www.phpmyadmin.net) for a web-based solution and SQLyog (www.webyog.com/sqlyog) for remote connections. Both are free solutions and will serve you well.
To connect to a MySQL database using PHP, you must make use of the mysql_connect function. Consider the following code, found within the file dbconnector.php, that will allow you to connect to the database:

//dbconnector.php
//Define the mysql connection variables.
define ("MYSQLHOST", "localhost");
define ("MYSQLUSER", "apressauth");
define ("MYSQLPASS", "tasks");
define ("MYSQLDB", "taskdb");
function opendatabase(){
$db = mysql_connect (MYSQLHOST,MYSQLUSER,MYSQLPASS);
try {
if (!$db){
$exceptionstring = "Error connecting to database:
";
$exceptionstring .= mysql_errno() . ": " . mysql_error();
throw new exception ($exceptionstring);
} else {
mysql_select_db (MYSQLDB,$db);
}
return $db;
} catch (exception $e) {
echo $e->getmessage();
die();
}
}
?>

As you can see, there are two parts to any database connection using MySQL. First, the mysql_connect function must attempt to make a connection to the database and validate the username and password. If a valid connection is made, a connection to the server will be retained. At this point, you must now specify which database you want to be working on. Since there could potentially be many databases assigned to each MySQL user, it is imperative that the script know which database to use. Using the mysql_select_db function, you can do just that. If everything goes properly, you should now have an open connection to the database, and you are ready to move on to the next stop: querying the database.

Introduction to MySQL

Obviously, in order to follow along with the examples in this chapter, you will need to
have a few applications running on your server. In order to make this example as flexible
as possible, I will show how to connect to MySQL using PHP code that will work on
servers that are compliant with PHP 5. Since MySQL 5 is extremely new as I write this,and not a great many server hosts have upgraded, I will show how to make it work from
MySQL 4 and up. Therefore, you will need PHP 5 and a version of MySQL 4 or higher
(3 will likely work just fine as well) installed on an Apache (or equivalent) server.

Before you can make use of MySQL, you must first research some core principles.
MySQL makes use of SQL (structured query language) when performing queries to the
database. It is therefore quite important to understand how SQL works, and what types of
queries will facilitate certain types of functionality. This book assumes that you know the
basics of implementing a database and running queries on it, as explaining the intricacies
of database management can quite easily fill a book on its own.

In the interest of creating an actual usable application, you will continue building the
application you started in Chapter 3. Basically, you will work to finalize the task management
solution by connecting the current Ajax-oriented JavaScript and PHP code with a
MySQL database so that you can actually draw information and save data dynamically to
a database. When finished, you will have a fully functional task management system that
can be used and implemented in any situation required.

Friday, December 28, 2007

AJAX Form Validation - Learn step by step final part

12. The class that supports the validation functionality is called Validate, and it is hosted in a script file called validate.class.php, which looks like this:

<?php

// load error handler and database configuration

require_once ('config.php');

// Class supports AJAX and PHP web form validation

class Validate

{

// stored database connection

private $mMysqli;

// constructor opens database connection

function __construct()

{

$this->mMysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

}

// destructor closes database connection

function __destruct()

{

$this->mMysqli->close();

}

// supports AJAX validation, verifies a single value

public function ValidateAJAX($inputValue, $fieldID)

{

// check which field is being validated and perform validation

switch($fieldID)

{

// Check if the username is valid

case 'txtUsername':

return $this->validateUserName($inputValue);

break;

// Check if the name is valid

case 'txtName':

return $this->validateName($inputValue);

break;

// Check if a gender was selected

case 'selGender':

return $this->validateGender($inputValue);

break;

// Check if birth month is valid

case 'selBthMonth':

return $this->validateBirthMonth($inputValue);

break;

// Check if birth day is valid

case 'txtBthDay':

return $this->validateBirthDay($inputValue);

break;

// Check if birth year is valid

case 'txtBthYear':

return $this->validateBirthYear($inputValue);

break;

// Check if email is valid

case 'txtEmail':

return $this->validateEmail($inputValue);

break;

// Check if phone is valid

case 'txtPhone':

return $this->validatePhone($inputValue);

break;

// Check if "I have read the terms" checkbox has been checked

case 'chkReadTerms':

return $this->validateReadTerms($inputValue);

break;

}

}

// validates all form fields on form submit

public function ValidatePHP()

{

// error flag, becomes 1 when errors are found.

$errorsExist = 0;

// clears the errors session flag

if (isset($_SESSION['errors']))

unset($_SESSION['errors']);

// By default all fields are considered valid

$_SESSION['errors']['txtUsername'] = 'hidden';

$_SESSION['errors']['txtName'] = 'hidden';

$_SESSION['errors']['selGender'] = 'hidden';

$_SESSION['errors']['selBthMonth'] = 'hidden';

$_SESSION['errors']['txtBthDay'] = 'hidden';

$_SESSION['errors']['txtBthYear'] = 'hidden';

$_SESSION['errors']['txtEmail'] = 'hidden';

$_SESSION['errors']['txtPhone'] = 'hidden';

$_SESSION['errors']['chkReadTerms'] = 'hidden';

// Validate username

if (!$this->validateUserName($_POST['txtUsername']))

{

$_SESSION['errors']['txtUsername'] = 'error';

$errorsExist = 1;

}

// Validate name

if (!$this->validateName($_POST['txtName']))

{

$_SESSION['errors']['txtName'] = 'error';

$errorsExist = 1;

}

// Validate gender

if (!$this->validateGender($_POST['selGender']))

{

$_SESSION['errors']['selGender'] = 'error';

$errorsExist = 1;

}

// Validate birth month

if (!$this->validateBirthMonth($_POST['selBthMonth']))

{

$_SESSION['errors']['selBthMonth'] = 'error';

$errorsExist = 1;

}

// Validate birth day

if (!$this->validateBirthDay($_POST['txtBthDay']))

{

$_SESSION['errors']['txtBthDay'] = 'error';

$errorsExist = 1;

}

// Validate birth year and date

if (!$this->validateBirthYear($_POST['selBthMonth'] . '#' .

$_POST['txtBthDay'] . '#' .

$_POST['txtBthYear']))

{

$_SESSION['errors']['txtBthYear'] = 'error';

$errorsExist = 1;

}

// Validate email

if (!$this->validateEmail($_POST['txtEmail']))

{

$_SESSION['errors']['txtEmail'] = 'error';

$errorsExist = 1;

}

// Validate phone

if (!$this->validatePhone($_POST['txtPhone']))

{

$_SESSION['errors']['txtPhone'] = 'error';

$errorsExist = 1;

}

// Validate read terms

if (!isset($_POST['chkReadTerms']) ||

!$this->validateReadTerms($_POST['chkReadTerms']))

{

$_SESSION['errors']['chkReadTerms'] = 'error';

$_SESSION['values']['chkReadTerms'] = '';

$errorsExist = 1;

}

// If no errors are found, point to a successful validation page

if ($errorsExist == 0)

{

return 'allok.php';

}

else

{

// If errors are found, save current user input

foreach ($_POST as $key => $value)

{

$_SESSION['values'][$key] = $_POST[$key];

}

return 'index.php';

}

}

// validate user name (must be empty, and must not be already registered)

private function validateUserName($value)

{

// trim and escape input value

$value = $this->mMysqli->real_escape_string(trim($value));

// empty user name is not valid

if ($value == null)

return 0; // not valid

// check if the username exists in the database

$query = $this->mMysqli->query('SELECT user_name FROM users ' .

'WHERE user_name="' . $value . '"');

if ($this->mMysqli->affected_rows > 0)

return '0'; // not valid

else

return '1'; // valid

}

// validate name

private function validateName($value)

{

// trim and escape input value

$value = trim($value);

// empty user name is not valid

if ($value)

return 1; // valid

else

return 0; // not valid

}

// validate gender

private function validateGender($value)

{

// user must have a gender

return ($value == '0') ? 0 : 1;

}

// validate birth month

private function validateBirthMonth($value)

{

// month must be non-null, and between 1 and 12

return ($value == '' || $value > 12 || $value < 1) ? 0 : 1;

}

// validate birth day

private function validateBirthDay($value)

{

// day must be non-null, and between 1 and 31

return ($value == '' || $value > 31 || $value < 1) ? 0 : 1;

}

// validate birth year and the whole date

private function validateBirthYear($value)

{

// valid birth year is between 1900 and 2000

// get whole date (mm#dd#yyyy)

$date = explode('#', $value);

// date can't be valid if there is no day, month, or year

if (!$date[0]) return 0;

if (!$date[1] || !is_numeric($date[1])) return 0;

if (!$date[2] || !is_numeric($date[2])) return 0;

// check the date

return (checkdate($date[0], $date[1], $date[2])) ? 1 : 0;

}

// validate email

private function validateEmail($value)

{

// valid email formats: *@*.*, *@*.*.*, *.*@*.*, *.*@*.*.*)

return (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $value)) ? 0 : 1;

}

// validate phone

private function validatePhone($value)

{

// valid phone format: ###-###-####

return (!eregi('^[0-9]{3}-*[0-9]{3}-*[0-9]{4}$', $value)) ? 0 : 1;

}

// check the user has read the terms of use

private function validateReadTerms($value)

{

// valid value is 'true'

return ($value == 'true' || $value == 'on') ? 1 : 0;

}

}

?>

13. Test your script by loading http://localhost/ajax/validate/index.php in a web browser.

AJAX Form Validation - Learn step by step PART - 5

9. It's time to add the business logic now. Start by creating config.php, with this code in it:

<?php

// defines database connection data

define('DB_HOST', 'localhost');

define('DB_USER', 'ajaxuser');

define('DB_PASSWORD', 'practical');

define('DB_DATABASE', 'ajax');

?>

10. Now create the error handler code in a file named error_handler.php:

<?php

// set the user error handler method to be error_handler

set_error_handler('error_handler', E_ALL);

// error handler function

function error_handler($errNo, $errStr, $errFile, $errLine)

{

// clear any output that has already been generated

if(ob_get_length()) ob_clean();

// output the error message

$error_message = 'ERRNO: ' . $errNo . chr(10) .

'TEXT: ' . $errStr . chr(10) .

'LOCATION: ' . $errFile .

', line ' . $errLine;

echo $error_message;

// prevent processing any more PHP scripts

exit;

}

?>

11. The PHP script that handles the client's AJAX calls, and also handles the validation on form submit, is validate.php:

<?php

// start PHP session

session_start();

// load error handling script and validation class

require_once ('error_handler.php');

require_once ('validate.class.php');

// Create new validator object

$validator = new Validate();

// read validation type (PHP or AJAX?)

$validationType = '';

if (isset($_GET['validationType']))

{

$validationType = $_GET['validationType'];

}

// AJAX validation or PHP validation?

if ($validationType == 'php')

{

// PHP validation is performed by the ValidatePHP method, which returns

// the page the visitor should be redirected to (which is allok.php if

// all the data is valid, or back to index.php if not)

header("Location:" . $validator->ValidatePHP());

}

else

{

// AJAX validation is performed by the ValidateAJAX method. The results

// are used to form an XML document that is sent back to the client

$response =

'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' .

'<response>' .

'<result>' .

$validator->ValidateAJAX($_POST['inputValue'], $_POST['fieldID']) .

'</result>' .

'<fieldid>' .

$_POST['fieldID'] .

'</fieldid>' .

'</response>';

// generate the response

if(ob_get_length()) ob_clean();

header('Content-Type: text/xml');

echo $response;

}

?>

AJAX Form Validation - Learn step by step PART - 4

7. Create a new file named allok.php, and add the following code to it: <?php

// clear any data saved in the session

session_start();

session_destroy();

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>AJAX Form Validation</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link href="validate.css" rel="stylesheet" type="text/css" />

</head>

<body>

Registration Successfull!<br />

<a href="index.php" title="Go back"><< Go back</a>

</body>

</html>

8. Create a file named validate.js. This file performs the client-side functionality, including the AJAX requests:

// holds an instance of XMLHttpRequest

var xmlHttp = createXmlHttpRequestObject();

// holds the remote server address

var serverAddress = "validate.php";

// when set to true, display detailed error messages

var showErrors = true;

// initialize the validation requests cache

var cache = new Array();

// creates an XMLHttpRequest instance

function createXmlHttpRequestObject()

{

// will store the reference to the XMLHttpRequest object

var xmlHttp;

// this should work for all browsers except IE6 and older

try

{

// try to create XMLHttpRequest object

xmlHttp = new XMLHttpRequest();

}

catch(e)

{

// assume IE6 or older

var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",

"MSXML2.XMLHTTP.5.0",

"MSXML2.XMLHTTP.4.0",

"MSXML2.XMLHTTP.3.0",

"MSXML2.XMLHTTP",

"Microsoft.XMLHTTP");

// try every id until one works

for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)

{

try

{

// try to create XMLHttpRequest object

xmlHttp = new ActiveXObject(XmlHttpVersions[i]);

}

catch (e) {} // ignore potential error

}

}

// return the created object or display an error message

if (!xmlHttp)

displayError("Error creating the XMLHttpRequest object.");

else

return xmlHttp;

}

// function that displays an error message

function displayError($message)

{

// ignore errors if showErrors is false

if (showErrors)

{

// turn error displaying Off

showErrors = false;

// display error message

alert("Error encountered: \n" + $message);

// retry validation after 10 seconds

setTimeout("validate();", 10000);

}

}

// the function handles the validation for any form field

function validate(inputValue, fieldID)

{

// only continue if xmlHttp isn't void

if (xmlHttp)

{

// if we received non-null parameters, we add them to cache in the

// form of the query string to be sent to the server for validation

if (fieldID)

{

// encode values for safely adding them to an HTTP request query string

inputValue = encodeURIComponent(inputValue);

fieldID = encodeURIComponent(fieldID);

// add the values to the queue

cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID);

}

// try to connect to the server

try

{

// continue only if the XMLHttpRequest object isn't busy

// and the cache is not empty

if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)

&& cache.length > 0)

{

// get a new set of parameters from the cache

var cacheEntry = cache.shift();

// make a server request to validate the extracted data

xmlHttp.open("POST", serverAddress, true);

xmlHttp.setRequestHeader("Content-Type",

"application/x-www-form-urlencoded");

xmlHttp.onreadystatechange = handleRequestStateChange;

xmlHttp.send(cacheEntry);

}

}

catch (e)

{

// display an error when failing to connect to the server

displayError(e.toString());

}

}

}

// function that handles the HTTP response

function handleRequestStateChange()

{

// when readyState is 4, we read the server response

if (xmlHttp.readyState == 4)

{

// continue only if HTTP status is "OK"

if (xmlHttp.status == 200)

{

try

{

// read the response from the server

readResponse();

}

catch(e)

{

// display error message

displayError(e.toString());

}

}

else

{

// display error message

displayError(xmlHttp.statusText);

}

}

}

// read server's response

function readResponse()

{

// retrieve the server's response

var response = xmlHttp.responseText;

// server error?

if (response.indexOf("ERRNO") >= 0

|| response.indexOf("error:") >= 0

|| response.length == 0)

throw(response.length == 0 ? "Server error." : response);

// get response in XML format (assume the response is valid XML)

responseXml = xmlHttp.responseXML;

// get the document element

xmlDoc = responseXml.documentElement;

result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;

fieldID = xmlDoc.getElementsByTagName("fieldid")[0].firstChild.data;

// find the HTML element that displays the error

message = document.getElementById(fieldID + "Failed");

// show the error or hide the error

message.className = (result == "0") ? "error" : "hidden";

// call validate() again, in case there are values left in the cache

setTimeout("validate();", 500);

}

// sets focus on the first field of the form

function setFocus()

{

document.getElementById("txtUsername").focus();

}