Getting started with PHP development with AJAX

Source: Internet
Author: User
Tags getting started with php

Asynchronous JavaScript and XML (Asynchronous JavaScript and XML, Ajax) are undoubtedly the most popular new Web technologies. In this article, we will use PHP and Simple Ajax Toolkit (Sajax) to create a Simple album as an online Web application. We first use the standard PHP development method to compile a simple album, and then use Sajax to turn it into an active Web application.

  Create a simple album

This article uses two methods to create a simple album: traditional Web applications and Sajax-based applications. We will write an album in PHP, read the content in a directory, and display a table composed of thumbnails. If you click a thumbnail, the image is fully expanded. Because traditional applications are compiled, each click is a new HTTP request, and the parameters are transmitted as part of the URL.

You will learn how to apply the Sajax library to photo albums and how Sajax can accelerate application development.

  Add a page sharer table

To access the album, users need to quickly view the photo. Because many large photos are not easily displayed on one page, you need to create a simple table that displays a small number of thumbnails each time. You also need to write navigation to help you move back and forth in the image list.

0 & image. height> 0) {if (image. width >=510) {this. width = 510; this. height = image. height * 510/image. width ;}}">
Figure 1. The page splitter provides a way to display User photos


   What is OpenAjax Alliance?

Before JavaOne Conference began in May 2006, representatives of 29 companies met in the Conference Room of Adobe Systems to prepare for a general determination of the future of Ajax. This group is called OpenAjax Alliance.

The Group made several decisions, the most significant of which was to name itself: OpenAjax Alliance. It also decided not to organize itself into a formal standard group, or an open source code-led organization like the Eclipse Foundation, so the form of the group itself is also informal for the moment. The Group agreed to hold approximately one teleconference every week.

OpenAjax Alliance focuses on three main aspects: by providing interoperability to reduce the risk of using Ajax, it ensures that the Ajax solution adheres to the open standard path and uses open source code technology to keep the Web open. The first task of the group was to find ways to establish and maintain interoperability between Ajax tools.

OpenAjax Alliance includes 31 technical companies, including IBM? , Adobe Systems, Eclipse Foundation, Google, Laszlo Systems Inc., Oracle, Red Hat Inc., And Zend Technologies Ltd ..

First, collect at least 20. jpg images and put them in a folder. Each image also has a thumbnail saved in a separate thumbnail folder. Although you can use the GD package to generate thumbnails (see references), this article assumes that you have prepared thumbnails. You can also use the photos and thumbnails provided in this article (see download ).

To complete the rest of this article, we assume that the image is saved in the/images subdirectory and the thumbnail is placed in/images/thumbnails. You can make appropriate changes in the Code. In addition, we also assume that the thumbnail and the corresponding image use the same name.

The page splitter should pass two parameters: start is the index number of the first photo displayed in alphabetical order, and step is the number of photos displayed.

List 1. album Viewer

/*
* Find a list of images in/images and provide thumbnails
*/
Function get_table ($ limit_start = 0, $ limit_step = 5 ){
$ Images = get_image_list ('images ');

// Generate navigation for Previous and Next buttons
// Code given below

$ Output. = '<table class = "image_table"> ';
$ Columns = 5;
Foreach ($ images as $ index => $ image ){

// Begin directory listing at item number $ limit_start
If ($ index <$ limit_start) continue;

// End directory listing at item number $ limit_end
If ($ index >=$ limit_start + $ limit_step) continue;

// Begin column
If ($ index-$ limit_start % $ columns = 0 ){
$ Output. = '<tr> ';
}

// Generate link to blown up image (see below)
$ Thumbnail = ' ';
$ Output. = '<td>'. get_image_link ($ thumbnail, $ index). '</td> ';

// Close column
If ($ index-$ limit_start % $ columns = $ columns-1 ){
$ Output. = '</tr> ';
}
}

$ Output. = '</table> ';

Return $ nav. $ output;
}
This table is very simple. It starts to traverse the image list from the index number $ limit_start. Then, the thumbnail of each image is placed, and each five images is taken as a line. When $ limit_start + $ limit_step is reached, the cycle ends.

This table is a visualized representation of the directory list. Therefore, a function is required to list all the images in the directory. The get_file_list () function in Listing 1 returns the list of all images in the/images directory using an indexed array. The following is an example.

Listing 2. get_file_list implementation

Function get_image_list ($ image_dir ){
$ D = dir ($ image_dir );
$ Files = array ();
If (! $ D) return null;

While (false! ==( $ File = $ d-> read ())){
// Getimagesize returns true only on valid images
If (@ getimagesize ($ image_dir. '/'. $ file )){
$ Files [] = $ file;
}
}
$ D-> close ();
Return $ files;
}


Note: The get_file_list () function is also used later in this article. It is important that the returned array remains unchanged no matter when this function is called. Because the provided implementation requires Directory Search, it is necessary to ensure that the specified files in the directory do not change, and each time they are sorted alphabetically.

  Navigation implementation

Although the table lists some images in the directory, you still need a method to view images that do not appear in the table. To truly implement the guide of the page splitter, a set of standard links are required: Home Page, Previous Page, next page, and last page.

Listing 3. Page sharer navigation

// Append navigation
$ Output = 'Min ($ limit_start + $ limit_step-1, count ($ images )).
'Of'. count ($ images). '<br/> ';

$ Prev_start = max (0, $ limit_start-$ limit_step );
If ($ limit_start> 0 ){
$ Output. = get_table_link ('<', 0, $ limit_step );
$ Output. = '|'. get_table_link ('prev ',
$ Prev_start, $ limit_step );
} Else {
$ Output. = '<| prev ';
}

// Append next button
$ Next_start = min ($ limit_start + $ limit_step, count ($ images ));
If ($ limit_start + $ limit_step <count ($ images )){
$ Output. = '|'. get_table_link ('Next', $ next_start, $ limit_step );
$ Output. = '|'. get_table_link ('>', (count ($ images)-$ limit_step), $ limit_step );
} Else {
$ Output. = '| Next |> ';
}

$ Output. = 'Finally, you must write the get_image_link () and get_table_link () functions to expand the thumbnail into a complete image (see Listing 4 ). Note that the index. php script (and the expand. php script to be created later) is called only in these two functions. This makes it easy to change the link function. In fact, only these two functions need to be modified when we integrate with Sajax below.

Listing 4. get_image_link and get_table_link implementation

Function get_table_link ($ title, $ start, $ step ){
$ Link = "index. php? Start = $ start & step = $ step ";
Return '<a href = "'. $ link. '">'. $ title. '</a> ';
}

Function get_image_link ($ title, $ index ){
$ Link = "expand. php? Index = $ index ";
Return '<a href = "'. $ link. '">'. $ title. '</a> ';
}
   Enlarge image

Now we have an available page splitter that provides you with thumbnails. The second function of the album is to allow users to click the thumbnail to view the full image. The get_image_link () function calls the expand. php script and we will compile it now. This script transmits the index of the file you want to expand. Therefore, you must list the Directory and obtain the appropriate file name here. The subsequent operation is simple. You only need to create the disease output image Tag.

Listing 5. get_image Function

Function get_image ($ index ){
$ Images = get_image_list ('images ');

// Generate navigation

$ Output. = ' ';
Return $ output;
}
The next step is to provide a navigation mechanism similar to the page splitter. Click "previous" to navigate to the image numbered $ index-1, click "Next" to navigate to the image numbered $ index + 1, and then return to the page splitter.

Listing 6. get_image navigation

$ Output. = '
If ($ index> 0 ){
$ Output. = get_image_link ('<', 0 );
$ Output. = '|'. get_image_link ('prev', $ index-1 );
} Else {
$ Output. = '<| prev ';
}

$ Output. = '|'. get_table_link ('up', $ index, 5 );

If ($ index <count ($ images )){
$ Output. = '|'. get_image_link ('Next', $ index + 1 );
$ Output. = '|'. get_image_link ('>', count ($ images ));
} Else {
$ Output. = '| Next |> ';
}

$ Output. = 'Finally, create a simple HTML container and name it expand. php.

Listing 7. get_image navigation

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Strict // EN"
Http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-strict.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Creating a simple picture album viewer </title>

<Style type = "text/css">
Body {text-align: center}
Table. image_table {margin: 0 auto 0 auto; width: 700px;
Padding: 10px; border: 1px solid # ccc; background: # eee ;}
Table. image_table td {padding: 5px}
Table. image_table a {display: block ;}
Table. image_table img {display: block; width: 120px;
Padding: 2px; border: 1px solid # ccc ;}
</Style>

</Head>
<Body>

<H1> Creating a simple picture album viewer <? Php

$ Index = isset ($ _ REQUEST ['index'])? $ _ REQUEST ['index']: 0;
Echo get_image ($ index );

?>
</Body>
</Html>
This completes the album. You can see all the images and navigate easily. Naturally, you can switch back and forth, or even return your favorite images through the bookmarks function.

0 & image. height> 0) {if (image. width >=510) {this. width = 510; this. height = image. height * 510/image. width ;}}">
Figure 2. Completed album

  Add Sajax

Now the Album provides basic navigation functions, and the images in the directory are indexed. The following shows that adding Sajax can improve programming and user experience.

If you have a basic understanding of Ajax, you 'd better be familiar with the basic knowledge of Sajax (see the tutorials in references ).

  Sajax, Ajax and traditional Web Applications
 
Now we have used the standard Web development model to develop applications. The two main functions are the page splitter and Image Viewer, which correspond to different PHP files respectively. Parameters are passed to the script as http get requests, and the script directly returns the page to the Web Client.

0 & image. height> 0) {if (image. width >=510) {this. width = 510; this. height = image. height * 510/image. width ;}}">
Figure 3. In traditional Web applications, three different requests call two pages


People in the Web development community know That Ajax allows asynchronous auxiliary requests to the server and displays results directly on the webpage (4 ). Unfortunately, even the simplest Ajax application implementation is a big task. Because Ajax is not a standardized technology, the implementation of Internet Explorer is different from that of other browsers (such as Firefox and Safari. In addition, programmers must write at least three functions to implement one function. These three functions are: the initial JavaScript for sending the HTTP request and the PHP script for returning the response, and another JavaScript function that processes these responses.

0 & image. height> 0) {if (image. width >=510) {this. width = 510; this. height = image. height * 510/image. width ;}}">
Figure 4. Ajax applications are responsible for all HTTP requests


Sajax built on the Ajax Library greatly simplifies this process by using a simple heuristic method: Every PHP function that the Web Client Needs to access is "exported" by Sajax ". If there is a PHP function named foo_bar (), Sajax exports the function as the JavaScript function x_foo_bar (). Any client call to x_foo_bar () is automatically forwarded to the foo_bar () on the server, and the output is passed to another JavaScript function. The short page in listing 8 demonstrates this feature. To run this example, You need to download the Sajax Library (see references ).

Listing 8. Sajax applications

<? Php
Require ("Sajax. php ");

Function foo_bar ($ param ){
Return "You typed: $ param ";
}

$ Sajax_request_type = "GET"; // Set HTTP request type to GET
Sajax_init (); // Prepare Sajax
Sajax_export ("foo_bar"); // foo_bar can now be called by client
Sajax_handle_client_request (); // Discussed below
?>
<Html>
<Head>
<Script language = "javascript">
<? Sajax_show_javascript ();?>
</Script>
</Head>
<Body>
<Form onSubmit = "x_foo_bar (this. input. value, alert); return false;">
<Input type = "text" name = "input"/>
</Form>
</Body>
</Html>
If you open the page in listing 8, Enter some content in the input box, and click Enter, the entered content will be displayed in a warning box. However, behind this seemingly simple web page, the x_foo_bar () JavaScript function will remotely call the foo_bar () function and pass the response to the JavaScript built-in function alert (). The last parameter of each Sajax export function is a response handler responsible for processing the output of foo_bar.

This example also illustrates another important feature of Sajax rapid development: Every function does not need to have a separate file, and the page actually calls itself, therefore, it is easier to track function calls (as shown in Figure 5 ). The x_foo_bar () function directly sends an Ajax request to the page, which contains the function name and parameters. The key is the sajax_handle_client_request () function, which intercepts all Sajax calls and automatically processes them.

0 & image. height> 0) {if (image. width >=510) {this. width = 510; this. height = image. height * 510/image. width ;}}">
Figure 5. Use the Sajax client to access multiple functions on the server through one page

 

  Connect Sajax to the album

With the code we just created, we will use Sajax to quickly convert the album from a multi-page application to an active Ajax application.

Because the album mainly has two functions: get_table () and get_image (), which are all functions to be exported using Sajax. In fact, to call these functions through Sajax, these functions basically do not need to be modified. Soon we will see that we only need to modify the generated link.

Listing 9. Head of the Sajax album

<? Php
Require ("Sajax. php ");

Function get_image () {}// Defined later
Function get_thumbs_table () {}// Defined later

// Standard Sajax stuff. Use Get, and export two
// Main functions to javascript
$ Sajax_request_type = "GET ";
Sajax_init ();
Sajax_export ("get_thumbs_table", "get_image ");
Sajax_handle_client_request ();
?>
For this article, the main part of the document is very simple. We will use the div and window IDs to display the server output.

Listing 10. display the div and window id output by the server

<Body>
<H1> Sajax photo album <Div id = "window"> </div>
</Body>
Finally, you need to write JavaScript callback functions. In this example, because all server outputs are directly output to the window div tag, simple callback functions can be reused. Add the callback function to the Sajax function call to obtain the header (head ).

Listing 11. Simple Headers

<Head>
<Title> Creating a Sajax photo album </title>
<Style type = "text/css">
Body {text-align: center}
Div # window {margin: 0 auto 0 auto; width: 700px;
Padding: 10px; border: 1px solid # ccc; background: # eee ;}
Table. image_table {margin: 0 auto 0 auto ;}
Table. image_table td {padding: 5px}
Table. image_table a {display: block ;}
Table. image_table img {display: block; width: 120px
Padding: 2px; border: 1px solid # ccc ;}
Img. full {display: block; margin: 0 auto 0 auto;
Width: 300px; border: 1px solid #000}
</Style>

<Script language = "javascript">
<? Sajax_show_javascript ();?>

// Outputs directly to the "window" div
Function to_window (output ){
Document. getElementById ("window"). innerHTML = output;
}

Window. onload = function (){
X get table to window );
};

</Script>
</Head>
The last step is to ensure that all links in the application are customized Sajax calls. Just take the code in the previous section and replace it with the following: href = "index. php? Start = 0 & step = 5 "changed to onclick =" x_get_table (0, 5, to_window) ", href =" expand. php? Index = 0 "to onclick =" x_get_image (0, to_window )".

And make the same changes in the corresponding function: get_image_link () and get_table_link (). This completes the conversion to Sajax (6 ). All links are converted into JavaScript calls corresponding to remote PHP calls. PHP uses the JavaScript response handler to_window () to directly output to the page.

The entire application is included in a page, and other functions (get_table (), get_image (), and so on) can be placed in a separate library file that cannot be accessed from the Web. In most Ajax applications, each request sent to the server must be processed by a separate script, or at least a very large handler script must be written to redirect requests. It may be very troublesome to gather all these files together. Sajax always requires only one file. In this file, you only need to define the functions we use. Sajax replaces the processing script.

0 & image. height> 0) {if (image. width >=510) {this. width = 510; this. height = image. height * 510/image. width ;}}">
Figure 6. Completed Sajax-based album (thumbnail)


We can see that the URL remains unchanged and brings more pleasant user experience. Window div is displayed in a gray box, and the content generated by Sajax is very clear. The script does not have to know itself or its location on the server, because all links eventually become directly called to the page's own JavaScript. Therefore, our code can be well modularized. We only need to keep the JavaScript and PHP functions on the same page, even if the page location changes.

 

  Extended album

It is so easy to use Sajax to turn our album into an active Web application. We need to spend some time adding some features to further illustrate how Sajax makes data retrieval from the server completely transparent. We will add metadata for the album so that users can add instructions for their images.

  Metadata

Albums without context descriptions are incomplete, such as the source and author of the photos. Therefore, we need to centralize the image to create a simple XML file. The root node is gallery, which contains any number of photo nodes. Each photo node is numbered by its file attribute. You can use any number of tags in the photo node to describe the photo, but only date, locale, and comment are used in this example.

Listing 12. XML files containing metadata

<? Xml version = "1.0"?>
<Gallery>
<Photo file = "image01.jpg">
<Date> August 6 and 2006 </date>
<Locale> Los Angeles, CA </locale>
<Comment> Here's a photo of my favorite celebrity </comment>
</Photo>
<Photo file = "image02.jpg">
<Date> August 7, 2006 </date>
<Locale> San Francisco, CA </locale>
<Comment> In SF, we got to ride the street cars </comment>
</Photo>
<Photo file = "image03.jpg">
<Date> August 8, 2006 </date>
<Locale> Portland, OR </locale>
<Comment> Time to end our road trip! </Comment>
</Photo>
</Gallery>
File Parsing is not included in the scope of this article. We assume that you are familiar with one of the many XML parsing methods in PHP. If you are not familiar with it, read the articles in references. We will not waste time explaining how to convert the file into HTML. As an exercise, readers can learn how to use XML files and generate HTML in the following code. The code in listing 13 uses the SimpleXML package that comes with PHP V5.

Listing 13. Metadata Functions

Function get_meta_data ($ file ){

// Using getimagesize, the server calculates the dimensions
List ($ width, $ height) = @ getimagesize ("images/$ file ");
$ Output = "<p> Width: {$ width} px, Height: {$ height} px </p> ";

// Use SimpleXML package in PHP_v5:
// Http://us3.php.net/manual/en/ref.simplexml.php
$ Xml = simplexml_load_file ("gallery. xml ");

Foreach ($ xml as $ photo ){
If ($ photo ['id'] = $ file ){
$ Output. =! Empty ($ photo-> date )? "<P> Date taken: {$ photo-> date} </p> ":'';
$ Output. =! Empty ($ photo-> locale )? "<P> Location: {$ photo-> locale}>/p> ":'';
$ Output. =! Empty ($ photo-> comment )? "<P> Comment: {$ photo-> comment} </p> ":'';
}
}
Return $ output;
Note that getimagesize () (a core PHP function without GD) is also used in the get_meta_data () function to calculate the image size.

Return to the get_image () function, which contains the list of file names generated by get_image_list. To search for metadata, you only need to pass the file name to the function.

Listing 14. Adding metadata

Function get_image ($ index ){
$ Images = get_image_list ('images ');

//...

$ Output. = ' ';
$ Output. = '<div id = "meta_data"> '.
Get_meta_data ($ images [$ index]). '</div> ';
Return $ output;
}
The result of the server request is displayed. Figure 7 shows an enlarged image with metadata.

0 & image. height> 0) {if (image. width >=510) {this. width = 510; this. height = image. height * 510/image. width ;}}">
Figure 7. album with metadata


   Conclusion

We can see that using Sajax can eliminate barriers between the client and the server. programmers can perform seamless remote function calls without worrying about transport layer, http get, and POST requests. We can spend more time writing PHP scripts for providing data and JavaScript For the presentation layer and control layer. In this album example, we have the client directly connect to the image database. By adding simple metadata, we can see how simple it is to allow users to directly access the information on the server without worrying about protocol issues.

Like all Ajax applications, our album has a fatal weakness: the browser's "Access History" is not used, because the function of the back button is broken. In Part 1 of the "using PHP to develop Ajax Applications" series, we will solve this problem by implementing the history buffer and status tracking mechanism.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.