I am available for freelance work - HIRE ME

Creative Problem Solving: PHP, jQuery and the Semi-Dynamic

posted by Matt Ward on Sep 13, 2010.

Have you ever been faced with a tricky design or development problem where the solution may not have been entirely obvious right off the bat? In this post we will look a situation like this that I was recently faced with, and how I used a combination of PHP and jQuery to form a solution.

The other day, I was asked to do something a little tricky on the Highland Marketing website. I had a static slider window that featured a number of “slides” promoting different services and unique parts of the site. It’s been working in its static form very nicely ever since the current design was implemented, with updates involving little more than creating, adding or subtracting images from the collection.

What I was asked to do was to make one of the slides dynamic.

Here’s a little background on the situation. We have a website (obviously) and part of that website includes a blog, which is home to a collection of really great content. It is not, however, getting as much readership as we might like, so we wanted to give it a bit more visibility on the home page. Since we already had one static slide dedicated to promoting the blog, the concept that was presented was to dynamically add the title of the most recent blog post into that slide.

Now, the entire site is built on the wonderful Concrete5 content management system – which is my favourite CMS for most brochure-based websites – while the blog, which was developed to stand along the main site, is driven by WordPress. Within Concrete5, the actual slider window was driven by a simple slideshow block, which allowed me to pick a number of images, give them each a link and then allow some simple (but custom) jQuery to scroll through them.

So, to sum up the challenge, I had to figure out a way to retrieve the latest post from a WordPress blog and somehow port the post title and link into a currently static, image-based slide on a Concrete5 website.

Let’s look at how I did it.

Weighing the Options

Right off the bat, I could conceive of a few different options, each of which I had to weigh and consider.

  1. Dynamically generated images – I’ve worked with server side image generation and manipulation in the past, and could probably have written a script to dynamically add the blog title into a generic image, and then serve the new image data to the requesting client.

    This would certainly have worked and made updating the CMS really easy, but I’ve never been overly happy with the way ImageMagick renders text, and the process would have involved a great deal of coding and extra work for the server – definitely not my ideal choice.

  2. HTML Slide Entirely in PHP – Another option would have been to actually change the slider from just images to be able to include full HTML blocks. These would allow me to dig into the actual PHP and try to devise a means of including the blog title and link in the appropriate place.

    While certainly a better alternative to server side image generation, this would still require some conditional customization of an already customized display template, all in order to be able to target the exact slide that I needed. It was certainly doable, but the PHP gymnastics that would be required were less than ideal.

  3. HTML Slide Using jQuery – A third option was very similar to the second, in that it would still require HTML blocks rather than just static images. However, instead of doing everything in the back end, I determined that I could take advantage of the already existing jQuery framework to update the contents of properties of targeted HTML elements.

    This would still require a bit of PHP in order to actually fetch the information that I needed, but that would be simple enough (as we will see).

If it’s not already obvious, I chose to go with the third option. It was the most elegant, the quickest to implement, and the one that made the best use of existing resources.

The Process

With that in mind, here’s how I went about pulling the whole thing together. Altogether, the full process basically involves fours basic steps, which are as follows:

Step 1 – Getting the Data

The very first thing that I needed to do was to actually get the data that I needed – in this case, the title of the most recent blog entry and the related URL. Whenever we need this kind of information, the most logical place to turn is to the RSS feed:

http://www.yoursite.com/blog/feed

Notice that I am using the standard WordPress feed. There’s really no need to go and use Feedburner in this instance, since there’s nothing we really want to track here.

Anyhow, in order to actually get the data, I used Magpie RSS, a PHP extension for parsing RSS feeds. I simply include the appropriate code file with the following line:

require_once 'rss_fetch.inc';

Then, I stored the feed URL to a variable and use the fetch_rss() function to actually grab and parse out the RSS data to a variable.

$myUrl = 'http://www.hiland.com/blog/feed/';
$myRss = fetch_rss($myUrl);

The variable $myRss now points to a fully populated PHP data structure. Before continuing, I set up a temporary visualization of that structure using the print_r() function:

print_r($myRss);

The resulting printout is far too long to include here, but through an analysis of the structure, I determined that the RSS object contained an array called ‘current_item’, which in turn contained values for ‘title’ and ‘link’. So, I used a few simple declarations to extract the data that I needed:

$myItems = $myRss->current_item;
$recentBlog = $myItems[title];
$recentBlogLink = $myItems[link];

That gives me the data I need in PHP variables, but I still need to make it accessible to the client-side jQuery. Now, I already mentioned that I was using existing resources for this solution and this is true. I already had the bulk of this code in place for a menu tool tip effect that I had implemented on the site (visit the home page and scroll over “blog” in the menu).

This is one added reason for going this particular route. Part of the code structure was already in place!

Step 2

Now, it’s time to get the information ready for us by jQuery, which is relatively easy to do. All I did was create an HTML <script> element in which I declared JavaScript variables to house the data. Then, I used the magic of PHP to include the appropriate bits of information:

var recentBlog = "<?php echo htmlentities($recentBlog); ?>";
var recentBlogLink = "<?php echo htmlentities($recentBlogLink); ?>";

That’s it. When the PHP is parsed, the proper values will be included between the quotation marks, and when the code is loaded by the browser, these variables will become available for use by JavaScript (and thus, jQuery).

Step 3

Now that we have our data available to us, we need a basic HTML structure for the dynamic slide, with elements that we can target. Here is the basic structure that I used.

<div class=”slide”>
  <div>
    <h3>Recently:</h3>
    <p><a class="recentBlogSlide" href="http://www.yoursite.com/blog/">
    <span>Loading most recent post...</span></a></p>
  </div>
  <a class="recentBlogSlide" href="http://www.yoursite.com/blog/">
    Learn More &raquo;</a>
</div>

The main <div> basically defines the boundaries of the slide. The next <div> defines the dynamic content area within that slide, so that it can be carefully positioned within the slide. The really important elements, however are the two <a> tags, since these are the elements that are going to be dynamically updated.

Notice that they both have the same class – ‘recentBlogSlide’. This will be important later on, when we get to the actual jQuery. The same is also true of the <span> element in the first link. I’ll explain more when we examine the actual jQuery calls, below.

In case you’re wondering why there are two links, the second is a standard “learn more” that appears on all the slides, and I wanted to keep it here, for the sake of consistency.

Step 4

Alright, with the HTML coded up, now it’s time to make the magic happen with the actual jQuery code. I am just going to go ahead and assume that we’ve already linked the jQuery library into the page, so we’ll start it all off with a basic jQuery callback function, which executes as soon as the DOM is finished loading:

$(function () {
  $(".recentBlogSlide").attr("href", recentBlogLink);
  $(".recentBlogSlide span").html(recentBlog);
  $("div.scrollable").scrollable({
    size: 1,
    clickable: false,
    onBeforeSeek: function() {
      $(".recentBlogSlide").attr("href", recentBlogLink);
      $(".recentBlogSlide").html(recentBlog);
  }});
});

There are a few important things going on here. First, we target both our links, changing the href attribute to match the value of our URL. This is where using the same class name is handy, because the jQuery syntax allows us to target them both with a single command.

Next, we change the inner HTML of our <span> element to contain the title of the most recent blog entry. The <span> exists for the purposes of specificity, allowing us to change the content of the first link, without effecting the second link.

You will also notice that we have another section of code, which initializes the Scrollable jQuery plugin. This snippet of code is used to initialize the sliding functionality for our box. Like many such plugins, this one uses a cloning function in order to achieve the effect of constant, circular scrolling. Unfortunately, when it clones, it seems to do so based on the original HTML, without the dynamic updates.

To fix this, I simply bound a custom function to the plugin’s built in onBeforeSeek event, which is triggered immediately before every new iteration of the slider. The function simply repeats the original substitutions, ensuring that every time the dynamic slide comes on the screen, the appropriate information will be there!

Wrap Up

So there you have the whole process for dynamically adding recent post information from a WordPress blog into a static HTML slide in Concrete5.To see it in action, be sure to check out the sliding panels on the Highland Marketing home page.

Here's a screen shot of the finished slide on the actual page

Here's a screen shot of the finished slide on the actual page

All told, this whole process took me just a few total hours to complete (though not all in a row), from the initial conceptualizing through to the final deployment of the solution. That also includes the time it took to tweak the slide background, to allow room for the blog title. Considering that dynamic visibility that it provides for the blog, we think it was time well spent.

If this little trick can be of some use to you, that would be awesome. More importantly, though, what I hope this article demonstrates is the power of creative problem solving. When faced with a puzzling problem, step back and look at your various options, then work to determine which solution is the most appropriate, most graceful and (in some cases) even the most expedient.

In this particular case, the solution involved a combination of PHP and jQuery in order to capture, transfer and ultimately deliver the information into the appropriate location. A different problem could involve a different methodology and/or blend of technologies, but that’s exactly where the creative element comes into play!

What creative solutions have you used to solve unique design or development challenges on your sites, or even between different sites? How do you approach these kinds of problems?

Post A Comment

Also from Echo Enduring Media:

An Unfolding Tale

About the Author

Matt Ward is a digital artist who lances freely under the moniker of Echo Enduring Media, and specializes in graphics design, illustration and writing. He is also the Creative Director for Highland Marketing, a creative direct marketing company based out of Waterloo, Ontario. You can follow Matt on Twitter

Like this post? Help Promote it!

Comments

Sep 14, 2010

Ian says:

Thanks for this, because it’s nice to hear how a *real life* problem is solved quickly, but reasonably cleanly, using the usual tools.

Sep 14, 2010

Aaron Hancock says:

I really like JQuery ajax! It makes my life SO much easier! :)

Sep 14, 2010

Imran Khan says:

very nice!!! i really need that article. yesterday i was having a problem but solution was not that clean =)

Thanks

Sep 24, 2010

Aneslin says:

usufull info for me, because I just satrt learning Jquery, thanks

Sep 26, 2010

Bryce Wisekal says:

Awesome!! Thank you so much for making this available. It was exactly what I needed to read!! Great work!!

Nov 9, 2010

Christian Marth says:

Thanks, Great article, have a similar problem and this approach looks like a great solution,

Would there be a way to externalize the dynamically created javascript?

Dec 8, 2010

Jason Anderson says:

Hi… Great post. I have just recently discovered Concrete5 CMS. My Webhost, ByteBob.com, installed it on their platform some months ago. I haven’t heard of it before.

Do you know any other webhosts that are offering Concrete5 cms hosting?

Dec 8, 2010

Matt Ward says:

I know that BlueHost allows it to be installed through their SimpleScripts service. I am currently working on a Concrete5 site where the host doesn’t have it installed, so I just installed it myself. Requires a bit of mySQL setup, but other than that the installation is super easy!

Dec 16, 2010

afaolek says:

Just heard about jQuery some weeks ago. Seems a fascinating scripting language. Can anyone refer me to a good site where I can learn it? Please send the link to my email afaolek@gmail.com cos I’m not always online. Thanx.

Leave a Comment

Links

  1. CSS Brigit | Creative Problem Solving: PHP, jQuery and the Semi-Dynamic

Top Commenters

Thanks so much to these awesome people for joining in on the discussion!

Copyright © Echo Enduring Media 2009-2014