Adding Functionality with jQuery and PHP Using Expression Web 4
- 12/29/2010
- Using jQuery in Expression Web
- Using the Expression Web PHP Tools
- Key Points
Using the Expression Web PHP Tools
PHP is a powerful, platform-independent server-side scripting language. As long as your server has PHP installed, you can use it regardless of the server type (such as Linux or Windows). When a browser requests a PHP page, the server executes the PHP script and sends the resulting HTML and other content to the browser. PHP pages may serve text, HTML, and script blocks, and function similarly to “Legacy ASP” pages. In other words, PHP pages can mix PHP code with HTML markup and other content.
Microsoft Expression Web 4 provides several tools to make working with PHP easier, and also provides assistance in creating and previewing PHP files. Programming in PHP is a very broad topic, and is well outside the scope of this book. This section serves purely as an introduction to the PHP tools in Expression Web.
In this portion of the chapter, you will become familiar with the Expression Web 4 tools for PHP and how to use them. You will use PHP to create a list of all the images in a folder automatically. You will also learn how to work with PHP functions, variables, and includes in Expression Web 4. At the end of the chapter, you will find references to more information about programming in PHP.
The PHP coverage in this book is not intended to be an example of best practices, or current PHP coding standards. It is here to expose the reader to the PHP tools available in Expression Web, particularly the Insert menu items, IntelliSense, and the Expression Development Server.
Using PHP in Expression Web
From the File menu, select New, and then select PHP. Expression Web creates a new PHP file named Untitled_1.php in your workspace.
From the Format menu, select Dynamic Web Template, and then select Attach Dynamic Web Template.
In the Attach Dynamic Web Template dialog box, browse to the site’s Images folder and double-click main.dwt. Click Close on the Update Confirmation alert.
The method of adding a Dynamic Web Template to a PHP file was originally shown in Chapter 3, so it may seem familiar to you.
In the Design pane, set your cursor inside the Content editable region. On the <DWT:editable> tab on the Quick Tag Selector, click the drop-down arrow, click Select Tag Contents, and then press Delete on your keyboard.
Type Automatic Image Gallery and then select the text. On the Styles drop-down menu, click Heading 1 <h1>, and then press Enter on your keyboard to create a new paragraph below your heading.
Click Save on the Common toolbar. In the Save As dialog box, make sure the root folder of the site is selected, and type Chapter8.php into the File Name field.
Click Save in the Save As dialog box.
Now that the PHP file is attached to the site’s Dynamic Web Template and saved, you need to add it to the site navigation by editing the Dynamic Web Template.
From the Format menu, select Dynamic Web Template, and then select Open Attached Dynamic Web Template.
The file main.dwt opens for editing in your workspace.
Set your cursor at the end of the text in the list item containing the link to the Chapter 8 file, and then press Enter on your keyboard to insert a new list item.
Type Chapter 8 (PHP) in the list item, and then triple-click the text to select it. Right-click the selected list item text, and from the context menu, select Hyperlink.
In the Insert Hyperlink dialog box, click Chapter8.php and then click OK to close the dialog box and insert the link.
Click Save All on the Common toolbar, click Yes on the File Update alert to save your navigation change to the DWT and all the pages it’s attached to, and then click Close on the Confirmation alert.
Close the Dynamic Web Template and return to Chapter8.php.
Notice how the navigation change you made in the DWT is now present on the new PHP file. The usefulness of a template for maintaining and managing a Web site can’t be overstated.
In the Design pane, set your cursor in the empty paragraph below the heading that you previously entered, and from the Insert menu, point to PHP and then click Code Block.
Set your cursor between the PHP tags in the Code pane, and press Enter twice on your keyboard to create an empty line. Then move your cursor to the new empty line between the PHP tags.
In the next few steps, you will use PHP to create an unordered list of all the files in a particular folder.
Enter the following code:
$dir = new DirectoryIterator('images/gallery1'); while($dir->valid()) { if(!$dir->isDot()) { print "<li><img src='images/gallery1/"; print $dir->current()."'/></li>"; } $dir->next(); }
The code retrieves all the files in the images/gallery1/ folder, and creates a set of HTML list items (<li></li>), to display those images, skipping the two “dot” directory items (the directory itself and its parent) that appear in all child directory listings. The code creates the list items and image tags, but you need to add the unordered list (<ul>) tag that surrounds the items to make the list render properly.
On the Quick Tag Selector, click the drop-down arrow on the <p> tag that’s surrounding your PHP code, and then click Edit Tag. On the Quick Tag Editor, change the <p> tag to a <ul> tag and then click the Checkmark button.
Click Save and then click Preview on the Common toolbar to run the PHP code and preview your page in a browser.
Take a few minutes to examine the page in a browser. Consider what you’ve been able to do with just a few lines of PHP. You have created a script that gets the file name of every file in a specific folder, and then displays them as a list of images. If you were to add additional image files to the /images/Gallery1/ folder, those images would also be included in the list; in other words, the list updates itself automatically.
Close the browser window and return to Chapter8.php in Expression Web.
Although the PHP worked, there are a couple of things that are sub-optimal. First, if you scroll through the list, you will see a broken image icon. This is because the PHP script looks for all the files in the Image folder, and one of those files is a hidden metadata folder that Expression Web uses to manage the site. PHP tries to display that directory in an image tag, which of course doesn’t work. Secondly, the bulleted list is hardly a “gallery.” In the next few steps you will remedy both those issues.
Improve the image list
Find your PHP code block from the previous steps in the Code pane. Change the code so that it looks like the following:
$dir = new DirectoryIterator('images/gallery1'); $FileType=".jpg"; while($dir->valid()) { if(!$dir->isDot()) { if(strpos($dir->current(),$FileType)) { print "<li><img src='images/gallery1/"; print $dir->current()."'/></li>"; } } $dir->next(); }
What you’ve done is added a variable to contain the file extension “.jpg” (the first bold line in the preceding code) and an if statement that makes sure the file name contains “.jpg” (the second bold line). The if test skips any file name that doesn’t include the extension “.jpg”—in other words, non-image files.
Click Save and then click Preview on the Common toolbar to check your modifications in a browser.
Notice that the previous broken image list item is gone. The list now includes only files with .jpg extensions, which is ideal for this particular gallery.
Close the browser and return to Expression Web.
In the next few steps, you will use more of the Expression Web PHP tools to make the code you’ve been working with more useful and reusable as well.
In the Code pane, locate the PHP code you have been working on. Select all of it (including the opening PHP delimiter “<?php” and the closing delimiter “?>”).
With the entire PHP block selected in the Code pane, right-click the highlighted code, and select Cut from the context menu.
In the next few steps, you will move this PHP code from Chapter8.php to its own file, and then bring it back into play via a PHP include.
From the File menu, select New, and then select PHP. Expression Web creates a new PHP file in your workspace.
Set your cursor in the Code pane of this new page, and press Ctrl+A on your keyboard to select all of the contents, and then press Delete on your keyboard.
Because you are creating a PHP file that will be included into a different page, you don’t want any head, body, or other tags to be present in it.
With the new PHP file completely empty, press Ctrl+V on your keyboard to paste in the PHP block that you cut from Chapter8.php.
Click Save on the Common toolbar, and in the Save As dialog box, name this file AutoGal.php. Save it in the root of the sample site.
Click the Chapter8.php tab at the top of your workspace to continue editing that file.
In the Code pane, set your cursor between the <ul> tags where you cut the PHP code block from the page. From the Insert menu, select PHP, and then click Include. In the Select File To Include dialog box, double-click the AutoGal.php file you saved in step 9.
The content from AutoGal.php will now be included in Chapter8.php via a server-side include. This is helpful, because you can use an include file on any page you want, and if you need to modify the file, you only need to make the modifications in one location.
Click the AutoGal.php tab at the top of your workspace to continue editing that file.
Remember what this code does: it looks in a specific folder, retrieves all the files in that folder, and then filters the list for just the .jpg files, creating an <img> tag for each .jpg file, and surrounding each item with <li></li> tags. So, you could insert it into any file you like but it would always do the same thing. That’s not very flexible. In the next few steps, you will modify this file so it’s much more flexible in a designer’s workflow.
The code returns the images as list items. Remember, you had to add the unordered list <ul> tag to surround the list before. To make things a little more sensible, you can add the unordered list tags to this include file. Enter a <ul> at the very beginning of the file, and a closing </ul> at the very end of the file.
Set your cursor after the opening PHP delimiter <?php, and then press Enter to create a new line.
Because you will replace some of the hard-coded variables in this block with variables you will be able to set in the page it’ll be included on, it’s important to make some notes here so that you and or anyone else will be able to easily see what’s going on.
On the new line just below your opening PHP tag, type the following comment (comments begin with two forward slashes in PHP).
// Don't forget to add the following variables before you include this file: //$TargetFolder $FileType $GalleryClass
By using the PHP comments feature (//), you can leave a message in the code file. The PHP engine ignores comment lines when it processes the page, so the comments will never appear in a browser, even if users view the HTML source of the page.
Change the <ul> tag at the top of this file to:
<ul class="<?php echo $GalleryClass ?>">
The echo command causes PHP to insert the contents of the following variable (in this case $GalleryClass). Because you can set this variable from outside the include file, that means you can define the unordered list class that’s in the host file. This will make it easier to apply any gallery style you like.
Change the next line from:
$dir = new DirectoryIterator('images/gallery1');
to:
$dir = new DirectoryIterator($TargetFolder);
You’re using a variable to set the script’s path to an appropriate folder. This way, you’ll be able to point the script at any folder you like from the page that contains the calls to the include file.
Change the following line from:
print "<li><img src='images/gallery1/";
to:
print "<li><img src='$TargetFolder";
Because you created a variable for the folder path, you want to replace the hard-coded path with the variable name.
Finally, remove the following line:
$FileType=".jpg";
You will define which file type to filter for in the Chapter8.php file, so it doesn’t belong in the include file now.
Click the Chapter8.php tab at the top of your workspace to switch back to that file. Scroll the Code pane to the <head> section and set your cursor just before the closing <!-- #EndEditable --> in the “doctitle” editable region, then press Enter on your keyboard to break to a new line. Enter the following code using the Expression Web IntelliSense pop-up:
<script type="text/javascript" src= "/files/jquery-ulslide/js/jquery.js"></script> <script type="text/javascript" src= "/files/jquery-ulslide/js/jquery.mousewheel.js"></script> <script type="text/javascript" src= "/files/jquery-ulslide/js/jquery.ulslide.js"></script> <script type="text/javascript"> $(function() { $('.slide1').ulslide({ width: 443, height: 'auto', bnext: '#e1_next', bprev: '#e1_prev', axis: 'y', mousewheel: true, autoslide: 3000}); $('.slide2').ulslide({ width: 443, height: 300, duration: 1000, affect: 'fade', bnext: '#e2_next', bprev: '#e2_prev', direction: 'f', duration: 350, autoslide: 3000}); }); </script>
The three <script> tags at the beginning of this code are includes for a jQuery library file and a plug-in called ULSlide. The actual JavaScript below that defines the appearance and behavior of the gallery. You can use other plug-ins that build a gallery based on an unordered list, or you can modify the PHP to create the chosen output that the plug-in requires.
Scroll down through the Code pane until you reach the area in the Content region where you have the PHP Include.
The final work here requires defining a few variables and removing the <ul> remnants from the earlier version.
Remove both the opening <ul> tag before the PHP include and the closing </ul> tag after it.
Enter the following code just above the PHP include file:
<?php $TargetFolder="images/gallery1/"; $FileType=".jpg"; $GalleryClass="slide1"; ?>
Click the Save All button, and then click the Preview button on the Common toolbar to test the gallery in a browser.
By using a small amount of PHP code and an easy-to-use jQuery plug-in, you have created a system that you can use over and over on any page or any number of pages you like. You’ve made it easy to turn a folder full of images into a self-maintaining image gallery of sorts.
Close the browser window and return to Expression Web.
Most of the work you just completed on the AutoGal.php include file was intended to make it more flexible. To explore that flexibility, you will now change the variables in Chapter8.php and cause the script to get a different kind of file, from a different folder, and apply a different gallery treatment to them.
Explore the power of generic include files
Return to the Chapter8.php file. Locate the variables you added to your page just above the PHP include statement and change them from this:
<?php $TargetFolder="images/gallery1/"; $FileType=".jpg"; $GalleryClass="slide1"; ?>
to this:
<?php $TargetFolder="images/gallery2/"; $FileType=".png"; $GalleryClass="slide2"; ?>
These new variables tell the script to look into a different folder (images/gallery2/), for a different type of picture file (.png), and then (by changing the $GalleryClass class name), apply a different style to the result.
Click Save and then click Preview on the Common toolbar to check your changes in a browser.
As you can see, by changing the variables that pertained to the folder you wanted to use, the file type that you wanted to find, and the jQuery effect you wanted to apply, you were able to include a totally different gallery into Chapter8.php. Using PHP variables and an include file makes it easy and flexible to drop a gallery on any page you like.
Close the browser and return to Expression Web.
PHP isn’t necessarily a “programmers only” tool. Like ASP.NET or any other server-side scripting, with a little knowledge and some creative use, designers can save a great deal of time, and do some truly interesting things automatically.
By using server-side code appropriately, you can create almost anything a site requires. Knowing how technologies work together helps a great deal. As you’ve seen in this section, combining PHP with a little jQuery can create interesting and useful results.