Friday, October 19, 2007

Show Hide Layer using a simple Javascript function

Are you looking for a simple JavaScript funciont to show/hide HTML elements? Take a look at this post.

This is the most simple Javascript function that I have written and used in some web projects usefull to show and hide a layer using CSS "display" property.

document.getElementById('id').style.display='block'

...to show the layer or...

document.getElementById('id').style.display='none'

... to hide the layer.

Download this script

How it works?
The script is very simple. The javascript function showlayer() has a parameter "layer", the layer ID that you want hide or show, for example:

<div id="myName">Antonio</div>


... in this example the layer ID is myName.

Now we will add a link that call the showlayer() function passing the layer ID:

<a href="#" onclick="javascript:showlayer('myName')">Hide / Show Layer </a>


Remember to add a link to show_layer.js into your page:

<script language="javascript" src="show_layer.js"></script>



The code
This is the code:

function showlayer(layer){
var myLayer = document.getElementById(layer).style.display;
if(myLayer=="none"){
document.getElementById(layer).style.display="block";
} else {
document.getElementById(layer).style.display="none";
}
}

Thursday, October 18, 2007

Time and Date difference using a PHP function

This is a simple PHP function dateTimeDiff() written for an application that I am developing, useful to get time and date difference between two date (a reference date and "now"), with a Digg-like style (ex: 12 min 20 sec ago). The mask of reference for each date is 2007-10-18 20:05:22, a standard MySQL datetime field.

Download this tutorial

How it works?
First, you have to include the file timeFunction.php into the PHP file that will use the function.

<?php include('timeFunction.php') ?>


... and you have to pass the data which it goes made the comparison:

dateTimeDiff($dataRef);


... where $dataRef is, for example, a value from a SQL query.


The code
This is the code of dateTimeDiff() PHP function:

<?php function dateTimeDiff($data_ref){

// Get the current date
$current_date = date('Y-m-d H:i:s');

// Extract from $current_date
$current_year = substr($current_date,0,4);
$current_month = substr($current_date,5,2);
$current_day = substr($current_date,8,2);

// Extract from $data_ref
$ref_year = substr($data_ref,0,4);
$ref_month = substr($data_ref,5,2);
$ref_day = substr($data_ref,8,2);

// create a string yyyymmdd 20071021
$tempMaxDate = $current_year . $current_month . $current_day;
$tempDataRef = $ref_year . $ref_month . $ref_day;

$tempDifference = $tempMaxDate-$tempDataRef;

// If the difference is GT 10 days show the date
if($tempDifference >= 10){
echo $data_ref;
} else {

// Extract $current_date H:m:ss
$current_hour = substr($current_date,11,2);
$current_min = substr($current_date,14,2);
$current_seconds = substr($current_date,17,2);

// Extract $data_ref Date H:m:ss
$ref_hour = substr($data_ref,11,2);
$ref_min = substr($data_ref,14,2);
$ref_seconds = substr($data_ref,17,2);

$hDf = $current_hour-$ref_hour;
$mDf = $current_min-$ref_min;
$sDf = $current_seconds-$ref_seconds;

// Show time difference ex: 2 min 54 sec ago.
if($dDf<1){
if($hDf>0){
if($mDf<0){
$mDf = 60 + $mDf;
$hDf = $hDf - 1;
echo $mDf . ' min ago';
} else {
echo $hDf. ' hr ' . $mDf . ' min ago';
}
} else {
if($mDf>0){
echo $mDf . ' min ' . $sDf . ' sec ago';
} else {
echo $sDf . ' sec ago';
}
}
} else {
echo $dDf . ' days ago';
}
?>

Login using Ajax and PHP

In the previous lesson we have seen how to realize an user login using Ajax and Coldfusion. Today's lesson will explains how to realize the same action using Ajax and PHP.

Download this tutorial

Introduction
In the site root we have to create these file, index.php,login.php, config.php and a folder AJAX with ajax_framework.js.


The workflow is the same that I have explained in the previous lesson: the user submit an HTML form with the username (in this example is the email address) and password. The form action call a javascript function, login(), in the ajax_framework.js file. This function pass with URL variables the input data to login.php page that execute a query and verify if the user exist. If the user exist return the user name, else return 0. The function loginReply() take this value returned from login.php and show a message into a layer of index.php.


Step 1: the Login HTML Form
The first step is to create the HTML form. How you can see, the code below is indipendent from the server-side scripting language and can be used for example with Coldfusion, PHP and other languages. In the first row we will include ajax_framework.js that contains javascript functions to enable ajax functionalities (XMLHttpRequest and other functions, in this example the login() function):

<!-- Include AJAX Framework -->
<script src="ajax/ajax_framework.js" language="javascript"></script>

<!-- Show Message for AJAX response -->
<div id="login_response"></div>

<!-- Form: the action="javascript:login()"call the javascript function "login" into ajax_framework.js -->
<form action="javascript:login()" method="post">
<input name="emailLogin" type="text" id="emailLogin" value=""/>
<input name="pswLogin" type="password" id="pswLogin" value=""/>
<input type="submit" name="Submit" value="Login"/>
</form>


Step 2: the javascript function login()
In this lesson we have see how enable the XMLHTTPRequest. In ajax_framework.js file we have added this code:

/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();


Now, in the same javascript file, we will add other lines of code for the function login():

/* -------------------------- */
/* LOGIN */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function login() {
// Optional: Show a waiting message in the layer with ID ajax_response
document.getElementById('login_response').innerHTML = "Loading..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var email = encodeURI(document.getElementById('emailLogin').value);
var psw = encodeURI(document.getElementById('pswLogin').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'login.php?email='+email+'&psw='+psw+'&nocache = '+nocache);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply() {
if(http.readyState == 4){
var response = http.responseText;
if(response == 0){
// if login fails
document.getElementById('login_response').innerHTML = 'Login failed! Verify user and password';
// else if login is ok show a message: "Welcome + the user name".
} else {
document.getElementById('login_response').innerHTML = 'Welcome'+response;
}
}
}


How you can see, the only change, respect to login() function of the previous tutorial with Coldfusion, is:

http.open('get', 'login.php?email='+email+'&psw='+psw+'&nocache = '+nocache);


...instead of:

http.open('get', 'login.cfm?email='+email+'&psw='+psw+'&nocache = '+nocache);


Step 3: login.php
In the previous step we have see how the login() function pass two variable (email and psw) to the page login.php, to execute a query into our database and verify that the user exists. This is the login.cfm page code:

<!-- Include Database connections info. -->
<?php include('config.php'); ?>

<!-- Verify if user exists for login -->
<?php
if(isset($_GET['email']) && isset($_GET['psw'])){

$email = $_GET['email'];
$psw = $_GET['psw'];

$getUser_sql = 'SELECT * FROM USER WHERE email="'. $email . '" AND psw = "' . $psw . '"';
$getUser = mysql_query($getUser_sql);
$getUser_result = mysql_fetch_assoc($getUser);
$getUser_RecordCount = mysql_num_rows($getUser);

if($getUser_RecordCount < 1){ echo '0';} else { echo $getUser_result['nick'];}
}


The tutorial is now ready to be tested in localhost server!
For info about PHP database connections and the file config.php included in the first row of login.php take a look to this post for other details.

Wednesday, October 17, 2007

Login using Ajax and Coldfusion

This lesson will explains how to implement a simple user login with Ajax and Coldfusion.

Download tutorial

Introduction
In the site root we have to create two file, index.cfm and login.cfm and a folder AJAX with ajax_framework.js.


This is the workflow: the user submit an HTML form with the username (in this example is the email address) and password. The form action call a javascript function, login(), in the ajax_framework.js file. This function pass with URL variables the input data to login.cfm page that execute a query and verify if the user exist. If the user exist return the user name, else return 0. The function loginReply() take this value returned from login.cfm and show a message into a layer of index.cfm.



Step 1: the Login HTML Form
The first step is to create the HTML form. How you can see, the code below is indipendent from the server-side scripting language and can be used for example with Coldfusion, PHP and other languages. In the first row we will include ajax_framework.js that contains javascript functions to enable ajax functionalities (XMLHttpRequest and other functions, in this example the login() function):

<!-- Include AJAX Framework -->
<script src="ajax/ajax_framework.js" language="javascript"></script>

<!-- Show Message for AJAX response -->
<div id="login_response"></div>

<!-- Form: the action="javascript:login()"call the javascript function "login" into ajax_framework.js -->
<form action="javascript:login()" method="post">
<input name="emailLogin" type="text" id="emailLogin" value=""/>
<input name="pswLogin" type="password" id="pswLogin" value=""/>
<input type="submit" name="Submit" value="Login"/>
</form>


Step 2: the javascript function Login()
In the previous lesson we have see how enable the XMLHTTPRequest. In ajax_framework.js file we have added this code:

/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();


Now, in the same javascript file, we will add other lines of code for the function login():

/* -------------------------- */
/* LOGIN */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function login() {
// Optional: Show a waiting message in the layer with ID ajax_response
document.getElementById('login_response').innerHTML = "Loading..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var email = encodeURI(document.getElementById('emailLogin').value);
var psw = encodeURI(document.getElementById('pswLogin').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'login.cfm?email='+email+'&psw='+psw+'&nocache = '+nocache);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply() {
if(http.readyState == 4){
var response = http.responseText;
if(response == 0){
// if login fails
document.getElementById('login_response').innerHTML = 'Login failed! Verify user and password';
// else if login is ok show a message: "Welcome + the user name".
} else {
document.getElementById('login_response').innerHTML = 'Welcome'+response;
}
}
}


Step 3: login.cfm
In the previous step we have see how the login() function pass two variable (email and psw) to the page login.cfm, to execute a query into our database and verify that the user exists. This is the login.cfm page code:

<!-- COLDFUSION login.cfm --->
<cfif isdefined('URL.email') AND isDefined ('URL.psw')>
<cfquery name="login" datasource="#dbName#">
SELECT *
FROM USER
WHERE email= '#URL.email#' and psw= '#URL.psw#'
</cfquery>
<!-- If record exists return the user name to the javascript funciont loginReply() -->
<cfif login.recordCount NEQ 0>
#login.name#
<!-- Else if record don't exists return 0 to the javascript function loginReply()-->
<cfelse>
0
</cfif>
</cfif>

Now our first Ajax example is ready to run!

Some details
If you use a DB access and you have a table called USER, when execute a query in the SQL FORM clause use "[USER]" and not only "USER" else you will have an error when coldfusion execute the query.

In the <cfquery name="login" datasource="#dbName#"> I have used a variable name for the datasource (#dbName#). This variable is defined in the Application.cfm file. See this post to more details about a coldfusion site structure. If you don't use a variable for the datasource name, replace with: <cfquery name="login" datasource="myDatasourceName"> where "myDatasourceName" will be the name of your datasource.

Tuesday, October 16, 2007

Start learning Ajax: XMLHttpRequest and site structure

In this lesson we will see how to organize our site to use Ajax into our semplified del.icio.us-like application.

Step 1: create XMLhttpRequest file

This is a short definition of XMLhttpRequest form Wikipedia:
XMLHttpRequest (XHR) is an API that can be used by JavaScript, and other web browser scripting languages to transfer XML and other text data to and from a web server using HTTP, by establishing an independent and asynchronous communication channel between a web page's Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats such as HTML, JSON or plain text.

XMLHttpRequest is an important part of the Ajax web development technique, and it is used by many websites to implement responsive and dynamic web applications.



In our site root we create a new folder AJAX and a file called ajax_framework.js where we will add in the next lessons all the javascript functions to use Ajax functionalities with our site.



Open ajax_framework.js and copy and past this code into the file to enable the XMLhttpReques into our ajax application (this code is standard and work with IE, Safari, and Firefox, on Windows based systems and Mac systems):


/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();


Save and close the file. Now, we are ready to work with some Ajax examples.

Monday, October 15, 2007

A simple introduction to Ajax

This picture is an simplified introduction about how Ajax works:



The user send a request that executes an action and the action's response is showed into a layer, identify by and ID, without reload the full page. For ex a layer with this id:

<div id="ajaxResponse"></div>


In the next lessons we will see how to create an XMLHttpRequest and some actions (login, modify data, insert data into a database table, load pages into a page layer...).

Sunday, October 14, 2007

Project a database: how to use PHP and SQL to create tables and relationships

This tutorial explains how to replicate in your remote server the database structure you created on your localhost.

A good way is to create a PHP file that executes SQL queries to create database tables and relationships. In this previous post we have seen how to define the relationships-entities model (tables, attributes, and relationships) for our database to be used in a simplified del.icio.us-like web application:





Step 1: add a DB folder into the site structure
In the site root we create a new folder DB and add a file create_database.php into this folder.



Step 2: create the php file
Open create_database.php on Dreamweaver and switch to Code View. Copy and paste this code inside the <body> tag.


<?php
//Connect to database
include('../config.php');

// CREATE TABLE USER

$sql= "CREATE TABLE USER (
id_user_pk INT NOT NULL AUTO_INCREMENT,
nick VARCHAR(40),
email VARCHAR(40),
password VARCHAR(20),
user_reg_date DATE,
PRIMARY KEY (id_user_pk)
) TYPE=INNODB";
mysql_query($sql);

// CREATE TABLE SITE

$sql="CREATE TABLE SITE (
id_site_pk INT NOT NULL AUTO_INCREMENT,
site_url VARCHAR(250),
site_description LONGTEXT,
site_data_reg DATA,
PRIMARY KEY
) TYPE=INNODB";
mysql_query($sql);

// CREATE TABLE SHARE

$sql="CREATE TABLE SHARE (
id_share_pk INT NOT NULL AUTO_INCREMENT,
id_user INT NOT NULL,
id_site INT NOT NULL,
submitted_by INT NOT NULL DEFAULT 0,
PRIMARY KEY (id_share_pk),
FOREIGN KEY (id_user) REFERENCES USER(id_user_pk) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (id_site) REFERENCES SITE(id_site_pk) ON UPDATE CASCADE ON DELETE CASCADE
) TYPE=INNODB";
mysql_query($sql);

// Close Connection
mysql_close($db_con);

?>


Now save the file and test it on localhost. Remember to include in create_database.php, connection's info (config.php) to your database.

In this way we can reuse create_database.php to copy your database structure on remote server when our project is ready to be published.