Hindi Songs

Search About PHP!!!

Thursday, July 9, 2009

Example explained - The PHP Page

The PHP page called by the JavaScript, is called "getuser.php".

The PHP script runs an SQL query against a MySQL database, and returns the result as HTML:

< ?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "


<>
<>Firstname< /th >
<>Lastname< /th >
<>Age
<>Hometown< /th >
<>Job< /th >
< /tr >";

while($row = mysql_fetch_array($result))
{
echo "<>";
echo "<>" . $row['FirstName'] . "< / td >";
echo "<>" . $row['LastName'] . "< / td >";
echo "<>" . $row['Age'] . "< / td >";
echo "<>" . $row['Hometown'] . "< / td >";
echo "<>" . $row['Job'] . "< / td >";
echo "< / tr >";
}
echo "< / table >";

mysql_close($con);
? >

When the query is sent from the JavaScript to the PHP page, the following happens:

1. PHP opens a connection to a MySQL server

2. The correct person is found

3. An HTML table is created, and filled with data, and sent back to the "txtHint" placeholder


The showUser() Function

When a person in the drop-down box is selected, the showUser() function executes the following:

1. Calls the GetXmlHttpObject() function to create an XMLHTTP object

2. Defines an URL (filename) to send to the server

3. Adds a parameter (q) to the URL with the content of the drop-down box

4. Adds a random number to prevent the server from using a cached file

5. Each time the readyState property changes, the stateChanged() function will be executed

6. Opens the XMLHTTP object with the given URL

7. Sends an HTTP request to the server

Example explained - The JavaScript code

This is the JavaScript code stored in the file "selectuser.js":

var xmlhttp;

function showUser(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getuser.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those.

Example explained - The HTML page

The HTML page contains a link to an external JavaScript, an HTML form, and a div element:

<>
<>
< type="text/javascript" src="selectuser.js">< /script >
< /head >
<>

<>
Select a User:
< name="users" onchange="showUser(this.value)">
< value="1">Peter Griffin< /option >
< value="2">Lois Griffin< /option >
< value="3">Glenn Quagmire< /option >

< /select >
< /form >
<>
< id="txtHint"><>Person info will be listed here.< /b >< /div >

< /body >
< /html >

As you can see it is just a simple HTML form with a drop down box called "customers".

The

below the form will be used as a placeholder for info retrieved from the web server.

When the user selects data, a function called "showUser()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showUser() is called.

Example explained - The MySQL Database

The database table we use in this example looks like this:

id

FirstName

LastName

Age

Hometown

Job

1

Peter

Griffin

41

Quahog

Brewery

2

Lois

Griffin

40

Newport

Piano Teacher

3

Joseph

Swanson

39

Quahog

Police Officer

4

Glenn

Quagmire

41

Quahog

Pilot

AJAX database example

The following example will demonstrate how a web page can fetch information from a database with AJAX technology.

Select a person:

Person info will be listed here.

Example explained - The PHP Page

The server paged called by the JavaScript, is a PHP file called "getcd.php".

The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and returns the result as HTML:

< ?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
{
echo($cd->item($i)->nodeName);
echo(": ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<>");
}
}
? >

When the CD query is sent from the JavaScript to the PHP page, the following happens:

1. PHP creates an XML DOM object

2. Find all elements that matches the name sent from the JavaScript

3. Output the album information (send to the "txtHint" placeholder)

The showUser() Function

When a person in the drop-down box is selected, the showUser() function executes the following:

1. Calls the GetXmlHttpObject() function to create an XMLHTTP object

2. Defines an URL (filename) to send to the server

3. Adds a parameter (q) to the URL with the content of the drop-down box

4. Adds a random number to prevent the server from using a cached file

5. Each time the readyState property changes, the stateChanged() function will be executed

6. Opens the XMLHTTP object with the given URL

7. Sends an HTTP request to the server

Example explained - The JavaScript code

This is the JavaScript code stored in the file "selectcd.js":

var xmlhttp

function showCD(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcd.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those.

AJAX XML example

The following example will demonstrate how a web page can fetch information from an XML file with AJAX technology.

Select a CD:

CD info will be listed here...


Example explained - The HTML page

The HTML page contains a link to an external JavaScript, an HTML form, and a div element:

<>
<>
< type="text/javascript" src="selectcd.js">< /script >
< /head >

<>

<>
Select a CD:
< name="cds" onchange="showCD(this.value)">
< value="Bob Dylan">Bob Dylan< /option >
< value="Bonnie Tyler">Bonnie Tyler< /option >
< value="Dolly Parton">Dolly Parton< /option >
< /select >
< /form >

< id="txtHint">
CD info will be listed here...< /b >< /div >

< /body >
< /html >

As you can see it is just a simple HTML form with a simple drop down box called "cds".

The <> below the form will be used as a placeholder for info retrieved from the web server.

When the user selects data, a function called "showCD" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCD is called.


The stateChanged() function

The stateChanged() function executes every time the state of the XMLHTTP object changes.

When the state changes to 4 ("complete"), the content of the txtHint placeholder is filled with the response text.


Example explained - The PHP page

The code in the "gethint.php" checks an array of names and returns the corresponding names to the client:

< ?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i {
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response
echo $response;
? >

If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:

1. Find a name matching the characters sent from the JavaScript

2. If no match were found, set the response string to "no suggestion"

3. If one or more matching names were found, set the response string to all these names

4. The response is sent to the "txtHint" placeholder

The GetXmlHttpObject() function

The showHint() function above calls a function named GetXmlHttpObject().

The purpose of the GetXmlHttpObject() function is to solve the problem of creating different XMLHTTP objects for different browsers.

The showHint() function

The showHint() function above is executed every time a character is entered in the "txt1" input field.

If there is input in the input field (str.length > 0), the showHint() function executes the following:

  • Calls the GetXmlHttpObject() function to create an XMLHTTP object
  • Defines the URL (filename) to send to the server
  • Adds a parameter (q) to the URL with the content of the input field
  • Adds a random number to prevent the server from using a cached file
  • Each time the readyState property changes, the stateChanged() function will be executed
  • Opens the XMLHTTP object with the given URL
  • Sends an HTTP request to the server

If the input field is empty, the function simply clears the content of the txtHint placeholder.

AJAX Suggest example

The following AJAX example will demonstrate how a web page can communicate with a web server while a user enters data into an HTML form.

Type a name in the input field below:

First name:

Suggestions:


Example explained - The HTML page

The HTML page contains a link to an external JavaScript, a simple HTML form, and a span element:

<>
<>
< type="text/javascript" src="clienthint.js">< /script >
< /head >
<>

<>
First Name: < type="text" id="txt1" onkeyup="showHint(this.value)">
< /form >
<>Suggestions: < id="txtHint">< /span >< /p >

< /body >
< /html >

The HTML form above has an input field called "txt1". An event attribute for this field defines a function to be triggered by the onkeyup event.

The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for data retrieved from the web server.

When a user inputs data, the function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time a user moves the finger away from a keyboard key inside the input field, the function showHint is called.


Example explained - The JavaScript code

This is the JavaScript code, stored in the file "clienthint.js":

var xmlhttp

function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

AJAX - Browser support

All new browsers use the built-in JavaScript XMLHttpRequest object to create an XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).

The JavaScript code for creating an XMLHttpRequest object:

if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}

The next chapter shows how to use the XMLHttpRequest object to communicate with a PHP server.

AJAX uses the XMLHttpRequest object

To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.

With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari).

PHP and AJAX

There is no such thing as an AJAX server. AJAX runs in your browser. AJAX uses HTTP requests to request small pieces of information from the server, instead of whole pages.

In our PHP tutorial we will demonstrate how a web page can communicate with a PHP web server online.

Start using AJAX today

There is nothing new to learn.

AJAX is based on existing standards. These standards have been used by developers for several years.

AJAX is about better Internet-applications

Internet-applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop.

However, Internet-applications are not always as "rich" and user-friendly as traditional desktop applications.

With AJAX, Internet applications can be made richer and more user-friendly.

AJAX is based on Internet standards

AJAX is based on the following web standards:

  • JavaScript
  • XML
  • HTML
  • CSS
AJAX applications are browser- and platform-independent.

AJAX = Asynchronous JavaScript and XML

AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications.

With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

The AJAX technique makes Internet applications smaller, faster and more user-friendly.

Using SimpleXML

Below is an XML file:

< ?xml version="1.0" encoding="ISO-8859-1"? >
<>
<>Tove< /to >
<>Jani< /from >
<>Reminder< /heading >
<>Don't forget me this weekend!< /body >
< /note >

We want to output the element names and data from the XML file above.

Here's what to do:

1. Load the XML file

2. Get the name of the first element

3. Create a loop that will trigger on each child node, using the children() function

4. Output the element name and data for each child node

Example

< ?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "
";

foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "
";
}
? >

The output of the code above will be:

note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!

Installation

As of PHP 5.0, the SimpleXML functions are part of the PHP core. There is no installation needed to use these functions.

What is SimpleXML?

SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML document's layout.

Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element.

SimpleXML converts the XML document into an object, like this:

  • Elements - Are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they're placed inside an array
  • Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name
  • Element Data - Text data from elements are converted to strings. If an element has more than one text node, they will be arranged in the order they are found

SimpleXML is fast and easy to use when performing basic tasks like:

  • Reading XML files
  • Extracting data from XML strings
  • Editing text nodes or attributes

However, when dealing with advanced XML, like namespaces, you are better off using the Expat parser or the XML DOM.

Looping through XML

We want to initialize the XML parser, load the XML, and loop through all elements of the element:

Example

< ?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "
";
}
? >

The output of the code above will be:

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =

In the example above you see that there are empty text nodes between each element.

When XML generates, it often contains white-spaces between the nodes. The XML DOM parser treats these as ordinary elements, and if you are not aware of them, they sometimes cause problems.

Load and Output XML

We want to initialize the XML parser, load the xml, and output it:

Example

< ?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
? >

The output of the code above will be:

Tove Jani Reminder Don't forget me this weekend!

If you select "View source" in the browser window, you will see the following HTML:

< ?xml version="1.0" encoding="ISO-8859-1"? >
<>
<>Tove< /to >
<>Jani< /from >
<>Reminder< /heading >
<>Don't forget me this weekend!< /body >
< /note >

The example above creates a DOMDocument-Object and loads the XML from "note.xml" into it.

Then the saveXML() function to puts the internal XML document into a string, so we can output it.

An XML File

The XML file below will be used in our example:

< ?xml version="1.0" encoding="ISO-8859-1"? >
<>
<>Tove< /to >
<>Jani< /from >
<>Reminder< /heading >
<>Don't forget me this weekend!< /body >
< /note >

Installation

The DOM XML parser functions are part of the PHP core. There is no installation needed to use these functions.

XML Parsing

To read and update - create and manipulate - an XML document, you will need an XML parser.

There are two basic types of XML parsers:

  • Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements
  • Event-based parser: Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it

The DOM parser is an tree-based parser.

Look at the following XML document fraction:

< ?xml version="1.0" encoding="ISO-8859-1"? >
<>Jani< /from >

The XML DOM sees the XML above as a tree structure:

  • Level 1: XML Document
  • Level 2: Root element:
  • Level 3: Text element: "Jani"

What is DOM?

The W3C DOM provides a standard set of objects for HTML and XML documents, and a standard interface for accessing and manipulating them.

The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM Level 1/2/3):

* Core DOM - defines a standard set of objects for any structured document
* XML DOM - defines a standard set of objects for XML documents
* HTML DOM - defines a standard set of objects for HTML documents

If you want to learn more about the XML DOM, please visit our
XML DOM tutorial.

Initializing the XML Parser

We want to initialize the XML parser in PHP, define some handlers for different XML events, and then parse the XML file.

Example

< ?php
//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case "NOTE":
echo "-- Note --<>";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}

//Function to use at the end of an element
function stop($parser,$element_name)
{
echo " <>";
}

//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}

//Specify element handler
xml_set_element_handler($parser,"start","stop");

//Specify data handler
xml_set_character_data_handler($parser,"char");

//Open XML file
$fp=fopen("test.xml","r");

//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}

//Free the XML parser
xml_parser_free($parser);
? >

The output of the code above will be:

-- Note --
To: Tove
From: Jani
Heading: Reminder
Message: Don't forget me this weekend!

How it works:

1. Initialize the XML parser with the xml_parser_create() function

2. Create functions to use with the different event handlers

3. Add the xml_set_element_handler() function to specify which function will be executed when the parser encounters the opening and closing tags

4. Add the xml_set_character_data_handler() function to specify which function will execute when the parser encounters character data

5. Parse the file "test.xml" with the xml_parse() function

6. In case of an error, add xml_error_string() function to convert an XML error to a textual description

7. Call the xml_parser_free() function to release the memory allocated with the xml_parser_create() function

Installation

The XML Expat parser functions are part of the PHP core. There is no installation needed to use these functions.


An XML File

The XML file below will be used in our example:

< ?xml version="1.0" encoding="ISO-8859-1"? >
<>
<>Tove< /to >
<>Jani< /from >
<>Reminder< /heading >
<>Don't forget me this weekend!< /body >
< /note >