Friday, October 26, 2007

Ajax: add a new element into a list using javascript insertBefore()

This tutorial is a very simple javascript function that add an element <li> into a list <ul> without reload the page. The element is passed from a input text field and is added on top of the list using insertBefore() javascript function.

Download this tutorial


Step 1: HTML code
First, we prepare the HTML code for our page:
  • <input> text field (with id="newElement") for add new element.
  • <ul id="myList"> the list into we will add new elements.
  • <div id="msg"></div> a layer that will show a message if the add action has been completed, or an error if the input field is emty.
Copy and paste this code into the <body> tag:

<style>
body{font-family:'Lucida Grande', Verdana, sans-serif; font-size:14px; color:#666666;}
a:link, a:visited{color:#0033CC;}
h3{border-bottom: solid 2px #DEDEDE; padding:6px 0; color:#000000;}
#msg{background:#FFFFCC; margin:10px; padding:4px; display:none;}
</style>

<h3>Add a new element into a <ul> list</h3>
Add a new element into the list (press "submit" button)<br><br>
<input name="newElement" id="newElement" type="text" value=""/>
<input type="button" value="submit" name="submit" onClick = "javascript:addElement()"/>

<div id="msg"></div>

<ul id="myList">
</ul>


Step 2: the javascript function addElement()
This is the javascript function that use insertBefore() to add the new element on top of the list.In the previous code, to te step 1, add this <script> between <h3>Add a new element into a <ul> list</h3> ... and ... </style> line.

<script language="javascript">
function addElement(){
// Get the value into the input text field
var element=document.getElementById('newElement').value;
if(element==""){
// Show an error message if the field is blank;
document.getElementById('msg').style.display="block";
document.getElementById('msg').innerHTML = "Error! Insert a description for the element";
}else{
// This is the <ul id="myList"> element that will contains the new elements
var container = document.getElementById('myList');
// Create a new <li> element for to insert inside <ul id="myList">
var new_element = document.createElement('li');
new_element.innerHTML = element;
container.insertBefore(new_element, container.firstChild);
// Show a message if the element has been added;
document.getElementById('msg').style.display="block";
document.getElementById('msg').innerHTML = "Elemend added!";
// Clean input field
document..getElementById('newElement').value="";
}
}
</script>


Save and try it!

Thursday, October 25, 2007

MyToDoList PHP: an open source to-do list written in PHP and AJAX

myToDoListPHP is a simple To-Do list that I am developing using PHP, MySQL and Ajax adding continuous improvements. You can add/delete tasks, and mark a task completed. You can also reuse the code in your projects to simplify your work.

Update history Update november 16, 2007
  • scriptacuolus effects and notes added october 27, 2007
  • sortable task with drag and drop added october 30, 2007
  • ajax search engine added november 1, 2007
  • update to version 0.3 november 11, 2007
  • update to ver 0.3a: I have solved some issues and added a filter for completed task november 14, 2007
  • update to version 0.4 november 15, 2007
  • update to version 0.5, added set task prioriy and % of completion november 16, 2007

Code Update
Download the new code here

Max Pozdeev MyTinyTodoList Website
MyTinyTodoList Demo




This is some application's screenshots:

Add users, tasks and notes:


The search engine, find task and user while you type:



Content
The package is composed from these files:
  • 1. todolist.php (the application's page)
  • 2. ajax_framework.js (javascript functions for Ajax functionalities)
  • 3. dbconnection.php (contains mySQL parameters for the connection to database. You have to change the default values with your parameters.)
  • 4. insertTask.php (insert a new task)
  • 5 deleteTask.php (delete a task)
  • 6 completeTask.php (mark a task complete)
  • 7. createDBtable.php (you can use this file to create automatically the database table)
  • 8. Scriptaculous folder (enable scriptaculous effects) october 27, 2007
  • 9. saveNote.php (you can add a note for each task) october 27, 2007
  • 10. in-showTask.php (code optimization) november 1, 2007
  • 11. insertUser.php (add a new user) november 11, 2007
  • 12. in-userRow.php (code optimization) november 11, 2007
  • 13. in-lineBar.php (code optimization) november 14, 2007
  • 14. in-sqlProperties.php (enable filter for completed tasks using an SQL parameter) november 14, 2007
  • 14. in-hideCompleteTask.php (save preference show/hide completed tasks into database) november 14, 2007
  • 15. in-modifyTask.php (modify task interface) november 15, 2007
  • 16. modifyTask.php (update task) november 15, 2007

Step 1: create a new MySQL database using myAdminPhp
First step, you have to create a new MySQL database using myAdminPHP and modify the connection's parameters ($db_host, $db_name, $username, $password) into the file dbconnection.php in this way:


<?php
// REQUIRED! Parameters to connecto to your DB
// CHANGE ONLY $db_host, $db_name, $username, $password
$db_host="localhost";
$db_name="woork";
$username="root";
$password="root";

// DON'T CHANGE THE REST!
$db_con=mysql_connect($db_host,$username,$password);
$connection_string=mysql_select_db($db_name);
mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);
?>


Step 2: create the database table using createDBtable.php
Now you can open createDBtable.php using your web browser in your localhost. This file will create a table TODOLIST to store the application's data. Verify on phpMyAdmin that the table has been created.

Step 3: run the application!
Open todolist.php with you browser and try the application!
You can reuse, modify, improve and distribute the code. For info please contact me.

Wednesday, October 24, 2007

Parsing Feed RSS to HTML using MagpieRSS and PHP

This simple tutorial explains how to parse a feed rss to HTML using MagpieRSS and some line of PHP code. MagpieRSS is an XML-based RSS parser in PHP and is included in the download file, into the folder parser.

Download this tutorial


The basic code
Create a new file index.php and copu and paste the following code into the <body> tag. This code parse the feed associated to $url variable in HTML and show in a list (<li> HTML tag) into a PHP page, the links to all items in the feed. In the first line of PHP code, you have to use require_once() to include rss_fetch.inc MagpieRSS file.

<? php
require_once('parser/rss_fetch.inc');
$url = 'http://feeds.feedburner.com/Woork';
$rss = fetch_rss( $url );
echo "Title: " . $rss->channel['title'];
echo "<ul>";
foreach ($rss->items as $item) {
echo "<li>". "<a href=\"". $item['link'] ."\">". $item['title'] ."</a></li>";
}
echo "</ul>";
?>


Limit the number of links to show in HTML
To limit the number of links that you can show in the page you can use a variable $count and a if statement:


<? php
require_once('parser/rss_fetch.inc');
$url = 'http://feeds.feedburner.com/Woork';
$rss = fetch_rss( $url );
echo "Title: " . $rss->channel['title'];
echo "<ul>";
// Limit at only 10 links
$count=1;
foreach ($rss->items as $item) {
echo "<li>". "<a href=\"". $item['link'] ."\">". $item['title'] ."</a></li>";
$count ++;
if($count==10){ break;}
}
echo "</ul>";
?>


Dowload the tutorial and try it!

Change the layer background color using a simple Javascript functions

These are two simple javascript functions that change on fly the background color of a layer without reload the page. To change the CSS background color with javascript we will use:

document.getElementById('ID').style.background ='background color'

Download this tutorial


1. Change background color
Copy and paste this code into <body> tag:

<script language="javascript">
function changeBg(idLayer){
idLayer_n = document.getElementById(idLayer);
if(idLayer_n.style.background!=''){
document.getElementById(idLayer).style.background ='#dedede';
document.getElementById('cb_text').innerHTML ='Changed! Click to restore';
} else {
document.getElementById(idLayer).style.background ='';
document.getElementById('cb_text').innerHTML ='Change Background color';
}
}
</script>

<div id='myLayer'>The script change the background color fo this layer!</div>
<a href="#" onclick="javascript:changeBg('myLayer')" id="cb_text">Change Background color</a>


2. Change background and text color with input field
This script change the layer background and text color using two input field to select the colors (esadecimal value).

To get the input field value with a javascript function we have to use:

document.getElementById('id').value;


Copy and paste this code into <body> tag:

<script language="javascript">
function changeBgInput(idLayer){
idLayer_n = document.getElementById(idLayer);
idColor_txt = document.getElementById('myColor_txt').value;
idColor_bg = document.getElementById('myColor_bg').value;
idLayer_n.style.color = idColor_txt;
idLayer_n.style.background = idColor_bg;
</script>

Text color: <br/>
<input type="text" id="myColor_txt" name="myColor_txt" value="#FFFFFF"><br/>
Background color: <br/>
<input type="text" id="myColor_bg" name="myColor_bg" value="#555555"><br/>
<a href="#" onClick="javascript:changeBgInput('myLayer');">Change text and background color</a>

Tuesday, October 23, 2007

Magnify text using Javascript

This is a simple javascript function that magnifies a text's size on fly, without reload the page.

The script use javascript to modify the CSS attribute, font-size that in javascript is rewritten with fontSize.
The script magnify the text until a max dimension set to 40px.

Download this script


The page code
Copy and past this code into the tag <body>;

<style type="text/css">
body{font-size:13px;}
</style>

<script language="javascript">
// Set the actual size to 13px equal to the value of font-size attribute
// on body CSS tag redefinition;
actualSize=13;
function magnifyText(idText){
// Increment of 10%
incrementSize=actualSize*(1.1);
// set a maximum size to expand text: for example 40 px;
if(incrementSize<40){
document.getElementById(idText).style.fontSize =incrementSize+'px';
actualSize=incrementSize;
}
}
</script>

<div id="myText">This is an example to magnify text size on fly.</div><br />
<a href="#" onclick="javascript:magnifyText('myText')">magnify</a>

Insert record into database using Ajax and Coldfusion

In the previous lesson we have seen how to use Ajax to insert a record into a database table using PHP. In this lesson we will explain how to implement the same tutorial using Coldfusion instead of PHP.

Download tutorial

How it works?
The structure is the same of the previous post. We have:
  1. index.cfm (contains a simple form with an input text)
  2. ajax_framework.js (the javascript function to enable ajax functionalities)
  3. insert.cfm (the Coldfusion code to save the record into a database table)

We have seen how that index.cfm and ajax_framework.js are indipendent from the script language (PHP, ASP, Coldfusion...).

Step 1: index.cfm
This is the code for index.cfm: a simple form that calls (in the action attribute) a javascript function, insertRecord(), in ajax_framework.js.

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

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

<!-- Form: the action="javascript:insert()"calls the javascript function "insert" into ajax_framework.js -->
<form action="javascript:insert()" method="post">
<input name="site_url" type="text" id="site_url" value=""/>
<input name="site_name" type="text" id="site_name" value=""/>
<input type="submit" name="Submit" value="Insert"/>
</form>


How you can see, nothing is changed respect to index.php of the previous post.

Step 2: the javascript function insert() in ajax_framework.js

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 insert():

/* -------------------------- */
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var site_url= encodeURI(document.getElementById('site_url').value);
var site_name = encodeURI(document.getElementById('site_name').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'insert.cfm?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('insert_response').innerHTML = 'Site added:'+response;
}
}


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

http.open('get', 'insert.cfm?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);


...instead of:

http.open('get', 'insert.php?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);


Step 3: insert.cfm


<cfif isDefined('URL.site_url') AND isDefined('URL.site_name')>
<cfset site_url= #URL.site_url#gt;
<cfset site_name= #URL.site_name#gt;
<!--- Change myDatasourceName with your datasource --->
<cfquery datasource="myDatasourceName">
INSERT INTO SITE (site_url, site_name) VALUES (
"#site_url#",
"#site_name#"
</cfquery>
<!--- Show the site name for the ajax response --->
<cfoutput>#site_name#</cfoutput>
<cfelse>
Error! Please fill all fields!
</cfif>


Save alla and try it in your localhost server.

Monday, October 22, 2007

Insert record into database using Ajax and PHP

This lesson will explains how to insert a record into a database table and show a message after insertion. In this example we will add a web site (URL and site name) into a table.

How does it works?
In the site root we have these files:
  1. index.php (contains a simple form with an input text)
  2. ajax_framework.js (the javascript function to enable ajax functionalities)
  3. insert.php (the PHP code to save the record into a database table)

Take a mind that index.php and ajax_framework.js are indipendent from the script language (PHP, ASP, Coldfusion...). For example index.php can be adopted also if you are using another script language changed only the extension (ex. from .php to .cfm if you use Coldfusion) without change the code.

Step 1: index.php
This is the code for index.php: a simple form that calls (in the action attribute) a javascript function, insertRecord(), in ajax_framework.js.

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

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

<!-- Form: the action="javascript:insert()"calls the javascript function "insert" into ajax_framework.js -->
<form action="javascript:insert()" method="post">
<input name="site_url" type="text" id="site_url" value=""/>
<input name="site_name" type="text" id="site_name" value=""/>
<input type="submit" name="Submit" value="Insert"/>
</form>


Step 2: the javascript function insert() in ajax_framework.js

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 insert():

/* -------------------------- */
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var site_url= encodeURI(document.getElementById('site_url').value);
var site_name = encodeURI(document.getElementById('site_name').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'insert.php?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('insert_response').innerHTML = 'Site added:'+response;
}
}


Step 3: insert.php
This is the insert.php page code:

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

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

$url= $_GET['site_url'];
$sitename= $_GET['site_name'];

$insertSite_sql = 'INSERT INTO SITE (site_url, site_name) VALUES('. $url. ',' . $sitename. ')';
$insertSite= mysql_query($insertSite_sql) or die(mysql_error());

<!-- If is set URL variables and insert is ok, show the site name -->
echo $sitename;
} else {
echo 'Error! Please fill all fileds!';
}
>


Save all, and try it in your localhost!