Enhancing your Site with PHP and jQuery

Exclusive offer: get 50% off this eBook here
PHP jQuery Cookbook

PHP jQuery Cookbook — Save 50%

Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery

£14.99    £7.50
by Vijay Joshi | December 2010 | Cookbooks Open Source PHP

In this article, by Vijay Joshi, author of PHP jQuery Cookbook, we will cover:

  • Sending cross-domain requests using server proxy
  • Making cross-domain requests with jQuery
  • Creating an endless scrolling page
  • Creating a jQuery plugin
  • Displaying RSS feeds with jQuery and PHP

 

PHP jQuery Cookbook

PHP jQuery Cookbook

Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery

  • Create rich and interactive web applications with PHP and jQuery
  • Debug and execute jQuery code on a live site
  • Design interactive forms and menus
  • Another title in the Packt Cookbook range, which will help you get to grips with PHP as well as jQuery
        Read more about this book      

(For more resources on this subject, see here.)

Introduction

In this article, we will look at some advanced techniques that can be used to enhance the functionality of web applications.

We will create a few examples where we will search for images the from Flickr and videos from YouTube using their respective APIs. We will parse a RSS feed XML using jQuery and learn to create an endless scrolling page like Google reader or the new interface of Twitter.

Besides this, you will also learn to create a jQuery plugin, which you can use independently in your applications.

Sending cross-domain requests using server proxy

Browsers do not allow scripts to send cross-domain requests due to security reasons. This means a script at domain http://www.abc.com cannot send AJAX requests to http://www.xyz.com.

This recipe will show how you can overcome this limitation by using a PHP script on the server side. We will create an example that will search Flickr for images. Flickr will return a JSON, which will be parsed by jQuery and images will be displayed on the page. The following screenshot shows a JSON response from Flickr:

Getting ready

Create a directory for this article and name it as Article9. In this directory, create a folder named Recipe1.

Also get an API key from Flickr by signing up at http://www.flickr.com/services/api/keys/.

How to do it...

  1. Create a file inside the Recipe1 folder and name it as index.html. Write the HTML code to create a form with three fields: tag, number of images, and image size. Also create an ul element inside which the results will be displayed.

    <html>
    <head>
    <title>Flickr Image Search</title>
    <style type="text/css">
    body { font-family:"Trebuchet MS",verdana,arial;width:900px;
    }
    fieldset { width:333px; }
    ul{ margin:0;padding:0;list-style:none; }
    li{ padding:5px; }
    span{ display:block;float:left;width:150px; }
    #results li{ float:left; }
    .error{ font-weight:bold; color:#ff0000; }
    </style>
    </head>
    <body>
    <form id="searchForm">
    <fieldset>
    <legend>Search Criteria</legend>
    <ul>
    <li>
    <span>Tag</span>
    <input type="text" name="tag" id="tag"/>
    </li>
    <li>
    <span>Number of images</span>
    <select name="numImages" id="numImages">
    <option value="20">20</option>
    <option value="30">30</option>
    <option value="40">40</option>
    <option value="50">50</option>
    </select>
    </li>
    <li>
    <span>Select a size</span>
    <select id="size">
    <option value="s">Small</option>
    <option value="t">Thumbnail</option>
    <option value="-">Medium</option>
    <option value="b">Large</option>
    <option value="o">Original</option>
    </select>
    </li>
    <li>
    <input type="button" value="Search" id="search"/>
    </li>
    </ul>
    </fieldset>
    </form>
    <ul id="results">
    </ul>
    </body>
    </html>

    The following screenshot shows the form created:

  2. Include the jquery.js file. Then, enter the jQuery code that will send the AJAX request to a PHP file search.php. Values of form elements will be posted with an AJAX request. A callback function showImages is also defined that actually reads the JSON response and displays the images on the page.

    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    {
    $('#search').click(function()
    {
    if($.trim($('#tag').val()) == '')
    {
    $('#results').html('<li class="error">Please provide
    search criteria</li>');
    return;
    }
    $.post(
    'search.php',
    $('#searchForm').serialize(),
    showImages,
    'json'
    );
    });

    function showImages(response)
    {
    if(response['stat'] == 'ok')
    {
    var photos = response.photos.photo;
    var str= '';
    $.each(photos, function(index,value)
    {
    var farmId = value.farm;
    var serverId = value.server;
    var id = value.id;
    var secret = value.secret;
    var size = $('#size').val();
    var title = value.title;

    var imageUrl = 'http://farm' + farmId +
    '.static.flickr.com/' + serverId + '/' + id + '_' +
    secret + '_' + size + '.jpg';
    str+= '<li>';
    str+= '<img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="' + imageUrl + '" alt="'
    + title + '" />';
    str+= '</li>';
    });

    $('#results').html(str);
    }
    else
    {
    $('#results').html('<li class="error">an error
    occured</li>');
    }
    }
    });
    </script>

  3. Create another file named search.php. The PHP code in this file will contact the Flickr API with specified search criteria. Flickr will return a JSON that will be sent back to the browser where jQuery will display it on the page.

    <?php

    define('API_KEY', 'your-API-key-here');
    $url = 'http://api.flickr.com/services/rest/?method=flickr.
    photos.search';
    $url.= '&api_key='.API_KEY;
    $url.= '&tags='.$_POST['tag'];
    $url.= '&per_page='.$_POST['numImages'];
    $url.= '&format=json';
    $url.= '&nojsoncallback=1';

    header('Content-Type:text/json;');
    echo file_get_contents($url);
    ?>

  4. Now, run the index.html file in your browser, enter a tag to search in the form, and select the number of images to be retrieved and image size. Click on the Search button. A few seconds later you will see the images from Flickr displayed on the page:

    <html>
    <head>
    <title>Youtube Video Search</title>
    <style type="text/css">
    body { font-family:"Trebuchet MS",verdana,arial;width:900px;
    }
    fieldset { width:333px; }
    ul{ margin:0;padding:0;list-style:none; }
    li{ padding:5px; }
    span{ display:block;float:left;width:150px; }
    #results ul li{ float:left; background-color:#483D8B;
    color:#fff;margin:5px; width:120px; }
    .error{ font-weight:bold; color:#ff0000; }
    img{ border:0}
    </style>
    </head>
    <body>
    <form id="searchForm">
    <fieldset>
    <legend>Search Criteria</legend>
    <ul>
    <li>
    <span>Enter query</span>
    <input type="text" id="query"/>
    </li>
    <li>
    <input type="button" value="Search" id="search"/>
    </li>
    </ul>
    </fieldset>
    </form>
    <div id="results">
    </div>
    </body>
    </html>

How it works...

On clicking the Search button, form values are sent to the PHP file search.php. Now, we have to contact Flickr and search for images. Flickr API provides several methods for accessing images. We will use the method flickr.photos.search to search by tag name. Along with method name we will have to send the following parameters in the URL:

  • api_key: An API key is mandatory. You can get one from:
  • http://www.flickr.com/services/api/keys/.

  • tags: The tags to search for. These can be comma-separated. This value will be the value of textbox tag.
  • per_page: Number of images in a page. This can be a maximum of 99. Its value will be the value of select box numImages.
  • format: It can be JSON, XML, and so on. For this example, we will use JSON.
  • nojsoncallback: Its value will be set to 1 if we don't want Flickr to wrap the JSON in a function wrapper.

Once the URL is complete we can contact Flickr to get results. To get the results' we will use the PHP function file_get_contents, which will get the results JSON from the specified URL. This JSON will be echoed to the browser.

jQuery will receive the JSON in callback function showImages. This function first checks the status of the response. If the response is OK, we get the photo elements from the response and we can iterate over them using jQuery's $.each method. To display an image, we will have to get its URL first, which will be created by combining different values of the photo object. According to Flickr API specification, an image URL can be constructed in the following manner:

http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[size].jpg

So we get the farmId, serverId, id, and secret from the photo element. The size can be one of the following:

  • s (small square)
  • t (thumbnail)
  • - (medium)
  • b (large)
  • o (original image)

We have already selected the image size from the select box in the form. By combining all these values, we now have the Flickr image URL. We wrap it in a li element and repeat the process for all images. Finally, we insert the constructed images into the results li.

Making cross-domain requests with jQuery

The previous recipe demonstrated the use of a PHP file as a proxy for querying cross-domain URLs. This recipe will show the use of JSONP to query cross-domain URLs from jQuery itself.

We will create an example that will search for the videos from YouTube and will display them in a list. Clicking on a video thumbnail will open a new window that will take the user to the YouTube website to show that video.

The following screenshot shows a sample JSON response from YouTube:

Getting ready

Create a folder named Recipe2 inside the Article9 directory.

How to do it...

  1. Create a file inside the Recipe2 folder and name it as index.html. Write the HTML code to create a form with a single field query and a DIV with results ID inside which the search results will be displayed.

    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    {
    $('#search').click(function()
    {
    var query = $.trim($('#query').val());
    if(query == '')
    {
    $('#results').html('<li class="error">Please enter
    a query.</li>');
    return;
    }
    $.get(
    'http://gdata.youtube.com/feeds/api/videos?q=' + query +
    '&alt=json-in-script',
    {},
    showVideoList,
    'jsonp'
    );
    });
    });
    function showVideoList(response)
    {
    var totalResults =
    response['feed']['openSearch$totalResults']['$t'];
    if(parseInt(totalResults,10) > 0)
    {
    var entries = response.feed.entry;
    var str = '<ul>';
    for(var i=1; i< entries.length; i++)
    {
    var value = entries[i];
    var title = value['title']['$t'];
    var mediaGroup = value['media$group'];
    var videoURL = mediaGroup['media$player'][0]['url'];

    var thumbnail = mediaGroup['media$thumbnail'][0]['url'];
    var thumbnailWidth =
    mediaGroup['media$thumbnail'][0]['width'];
    var thumbnailHeight =
    mediaGroup['media$thumbnail'][0]['height'];
    var numComments =
    value['gd$comments']['gd$feedLink']['countHint'];
    var rating =
    parseFloat(value['gd$rating']['average']).toFixed(2);
    str+= '<li>';
    str+= '<a href="' + videoURL + '" target="_blank">';
    str+= '<img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="'+thumbNail+'" width="'+thumbNailWidth+'"
    height="'+thumbNailWidth+'" title="' + title + '" />';
    str+= '</a>';
    str+= '<hr>';
    str+= '<p style="width: 120px; font-size: 12px;">Comments:
    ' + numComments + '';
    str+= '<br/>';
    str+= 'Rating: ' + rating;
    str+= '</p>';

    str+= '</li>';
    }
    str+= '</ul>';
    $('#results').html(str);
    }
    else
    {
    $('#results').html('<li class="error">No results.</li>');
    }
    }
    </script>

  2. Include the jquery.js file before closing the &ltbody> tag. Now, write the jQuery code that will take the search query from the textbox and will try to retrieve the results from YouTube. A callback function called showVideoList will get the response and will create a list of videos from the response.

    http://gdata.youtube.com/feeds/api/videos?q=' + query +
    '&alt=json-in-script

  3. All done, and we are now ready to search YouTube. Run the index.html file in your browser and enter a search query. Click on the Search button and you will see a list of videos with a number of comments and a rating for each video.

How it works...

script tags are an exception to cross-browser origin policy. We can take advantage of this by requesting the URL from the src attribute of a script tag and by wrapping the raw response in a callback function. In this way the response becomes JavaScript code instead of data. This code can now be executed on the browser.

The URL for YouTube video search is as follows:

http://gdata.youtube.com/feeds/api/videos?q=' + query + '&alt=json-in-script

Parameter q is the query that we entered in the textbox and alt is the type of response we want. Since we are using JSONP instead of JSON, the value for alt is defined as json-in-script as per YouTube API specification. On getting the response, the callback function showVideoList executes. It checks whether any results are available or not. If none are found, an error message is displayed. Otherwise, we get all the entry elements and iterate over them using a for loop. For each video entry, we get the videoURL, thumbnail, thumbnailWidth, thumbnailHeight, numComments, and rating. Then we create the HTML from these variables with a list item for each video. For each video an anchor is created with href set to videoURL. The video thumbnail is put inside the anchor and a p tag is created where we display the number of comments and rating for a particular video. After the HTML has been created, it is inserted in the DIV with ID results.

There's more...

About JSONP

You can read more about JSONP at the following websites:

PHP jQuery Cookbook Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery
Published: December 2010
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on this subject, see here.)

Creating an endless scrolling page

If you use Google reader or the new Twitter then you will understand what I am talking about. In both of these applications when you scroll and reach the bottom of the page they automatically load content that is appended to the bottom of the page. This behavior eliminates the need for pagination; the previous and the next buttons.

We will create an example that will have a similar functionality. On reaching the bottom of a page, an AJAX request will load data from a PHP script and will append it to the bottom of the page.

Getting ready

Create a folder named Recipe3 inside the Article9 directory.

How to do it...

  1. Create a new file named index.html inside the Recipe3 folder. In this file, create a DIV with container ID along with some paragraphs so that the page becomes long enough for scrolling. Next to it create another paragraph that will show a loading text when data will be fetched from the server.

    <html>
    <head>
    <title>Endless Scroll</title>
    <style type="text/css">
    body{ font-family: "Trebuchet MS",verdana,arial;}
    #loading{ display:none; font-weight:bold;color:#FF0000;}
    p{padding:10px;}
    </style>

    </head>
    <body>
    <div id="container">
    <p>Test Paragraph 1</p>
    <p>Test Paragraph 2</p>
    <p>Test Paragraph 3</p>
    <p>Test Paragraph 4</p>
    <p>Test Paragraph 5</p>
    <p>Test Paragraph 6</p>
    <p>Test Paragraph 7</p>
    <p>Test Paragraph 8</p>
    <p>Test Paragraph 9</p>
    <p>Test Paragraph 10</p>
    <p>Test Paragraph 11</p>
    <p>Test Paragraph 12</p>
    <p>Test Paragraph 13</p>
    <p>Test Paragraph 14</p>
    <p>Test Paragraph 15</p>
    <p>Test Paragraph 16</p>
    <p>Test Paragraph 17</p>
    <p>Test Paragraph 18</p>
    <p>Test Paragraph 19</p>
    <p>Test Paragraph 20</p>
    </div>
    <p id="loading">loading data... </p>
    <p>&nbsp;</p>
    </body>
    </html>

  2. Include the jquery.js file before closing the &ltbody> tag. Write the jQuery code that will add event handlers for window scroll. If the user reaches the window bottom while scrolling or using arrow keys, the code will send an AJAX request to a PHP file, data.php, to load the data. This data will be appended to the existing data.

    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    {
    $(window).scroll(loadData);
    });

    var counter = 0;
    function loadData()
    {
    if(counter < 5)
    {
    if (isUserAtBottom())
    {
    getData();
    }
    }
    }
    function isUserAtBottom()
    {
    return ((($(document).height() - $(window).height()) -
    $(window).scrollTop()) <= 50) ? true : false;
    }
    function getData()
    {
    $(window).unbind('scroll');
    $('#loading').show();

    $.get(
    'data.php',
    {},
    function(response)
    {
    counter++;
    $('#loading').hide();
    $('#container').append(response);
    $(window).scroll(loadData);
    });
    }
    </script>

  3. On the server side, create a new PHP file data.php. In this file, simply echo a line that will be sent to the browser.

    <?php
    sleep(2);
    echo '<p>This data has been <br/>loaded from server...</p>';
    ?>

  4. Run the index.html file in your browser. You will see a long list of paragraphs. Now scroll down the page using the mouse wheel or arrow keys. When you reach the bottom a loading indicator will appear.

  5. After the data has been loaded, this indicator will disappear and data received from the PHP script will be appended to the existing one.

How it works...

First of all, we attached a scroll event handler to the window element. On scrolling the page through a mouse or arrow keys, the handler function loadData is called. Now before we load any data we will have to make sure that the user is indeed at the bottom of the page. For this purpose, a function isUserAtBottom is defined. To determine this we use following code:

return ((($(document).height() - $(window).height()) - $(window).
scrollTop()) <= 50) ? true : false;

$(document).height() is the height of the complete HTML page. $(window).height() is the height of the visible area of the browser or the viewport. $(window).scrollTop() indicates the vertical position of the scroll bar from the top. We have calculated the resulting value by subtracting the window height and scrollbar position from the document's total height. If this value is less than 50, that is, the user is 50 pixels above from the bottom of the browser, we return true, otherwise false.

Once we know that the user is at the bottom we call getData() function. This function first unbinds the scroll event from the window so that no more requests could be processed until the current one completes. Then the loading indicator is displayed and an AJAX request is sent to data.php file. In this example, this file echoes a single line. When the response is received in callback function, loading indicator is hidden and the received data is appended to the DIV container. Scroll event is then again attached to the window that will allow the user to load more data. This process will continue until the value of variable counter is less than five. It means data will be fetched from the server a maximum of five times.

There's more...

Loading data from other sources

In this example, we have echoed a single line from PHP file. In real world applications, data will be fetched from databases or APIs. You should also allow a condition when there is no more data to load and show appropriate response to the user.

Creating a jQuery plugin

This recipe will explain how you can create a simple jQuery plugin. The user will be able to enter two numbers and the plugin will count from the first number to the second number while animating just like a stopwatch changes. We will call it Cash Counter. You will also be able to specify how fast or slow the animation runs.

Getting ready

Create a folder Recipe4 inside the Article9 directory.

How to do it...

  1. Create a file named index.html inside Recipe4 folder. In this file, create two text boxes to enter starting and end numbers, an h1 element to display the number as it changes, and a button to initiate the process.

    <html>
    <head>
    <title>Cash Counter</title>
    <style type="text/css">
    body{ font-family:"Trebuchet MS",verdana,arial;
    width:900px;margin:0 auto; }
    ul{ list-style:none;padding:10px; }
    label{ display:block;float:left;width:75px; }
    </style>
    </head>
    <body>
    <ul>
    <li>
    <label>Start :</label><input type="text" id="start"/>
    </li>
    <li>
    <label>End :</label><input type="text" id="end"/>
    </li>
    <li>
    <h1 id="container"></h1>
    </li>
    <li>
    <input type="button" id="change" value="Change" />
    </li>
    </ul>
    </body>
    </html>

  2. Next, create a new JavaScript file and name it as jquery.counter.js. This file will contain the code for plugin. Put the following code for creating the plugin:

    (function( $ )
    {
    $.fn.cashCounter = function(options)
    {
    return this.each(function()
    {
    settings = $.extend
    (
    {
    start: 0,
    end: 0,
    step: .5
    },
    options
    );
    var e = $(this);
    if(isNaN(settings.start) || isNaN(settings.end) ||
    ((settings.start) == (settings.end)))
    {
    return this;
    }
    settings.increasing = (settings.start < settings.end) ?
    true : false;
    if(settings.increasing)
    {
    if(settings.start >= settings.end)
    {
    return this;
    }
    }
    else
    {
    if(settings.start <= settings.end)
    {
    return this;
    }
    }
    var diff = parseInt(settings.end,10) -
    parseInt(settings.start,10);
    var changeBy;
    if(settings.increasing)
    {
    changeBy = Math.ceil(diff * settings.step);
    }
    else
    {
    changeBy = Math.floor(diff * settings.step);
    }
    settings.start = parseInt(settings.start,10) + changeBy;
    e.html(settings.start);
    setTimeout(function()
    {
    e.cashCounter(settings);
    }, 100);

    });//each
    };
    })( jQuery );

  3. Coming back to index.html again, include the jQuery.js file first and then include the just created plugin file jQuery.counter.js. After that write the code for the click handler for the button that will take the values from textboxes and will run the plugin.

    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../jquery.js"></script>
    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="jquery.counter.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    {
    $('#change').click(function()
    {
    if($('#start').val() != '' && $('#end').val() != '')
    {
    var startVal = $('#start').val();
    var endVal = $('#end').val();
    $('#container').cashCounter
    (
    {
    start: startVal,
    end: endVal,
    step: .2
    }
    );
    }
    else
    {
    $('#container').html('Please enter start and
    end values.');
    }
    });
    });
    </script>

  4. Open your browser and run the index.html file. Enter the Start and End numbers in the textboxes and click on the Change button. The counting will start from the start value until the end value. Since it is not possible to show the animated image, the following screenshot captures the process in between. Also try changing the step value to see how fast or slow the counting happens:

PHP jQuery Cookbook Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery
Published: December 2010
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on this subject, see here.)

How it works...

The cashCounter plugin will accept three parameters while initializing it. start, end, and step. While start and end values are obvious, step will be used to determine how fast the counting runs. Its value can vary from 0.1 to 0.9 with 0.1 being the fastest speed.

A jQuery plugin begins by extending the jQuery.fn object. We want to name our plugin cashCounter, so we wrap it in the following:

jQuery.fn.cashCounter = function(options)
{
};

All of the plugin code will go inside this block. Next is the return this.each(function() {} ) line. It ensures that a jQuery object is returned to the calling function. This will help maintain the chaining of elements as supported by jQuery.

Next is the settings object that defines the default values for a plugin if they are not supplied. In case these values are supplied we extend these by merging the user provided options object with the default settings. By default, both start and end have a zero value and the value for step is 5.

With all the settings in place we can now write the functionality. If start or end values are not numbers or if start is equal to end we stop the code execution by returning from the function.

Then, we set a property increasing for the settings object. If the end value is greater than start we set it to true, otherwise false. In case increasing is true, if the start value exceeds the end value we terminate further execution. Similarly, if increasing is false we terminate if the end value exceeds the start value.

Then, we find the difference of start and end values and calculate a variable changeBy, which will increase or decrease the start value depending on the variable step. The new start value is set and also inserted into the requesting element, h1 container in this case.

Finally, we call the JavaScript setTimeout function that calls the cashCounter function recursively after 100 milliseconds. On each execution, if conditions will be checked and once the end value is reached, the control will exit out of application.

Displaying RSS feeds with jQuery and PHP

In this recipe we will fetch a Really Simple Syndication (RSS) feed of a blog using PHP and then display it in the page using jQuery. RSS is a standard format for publishing feeds and there are several formats of RSS feeds. The feed we will use is in RSS2.0 and its standard structure is shown in the following screenshot:

Getting ready

Create a folder named Recipe5 inside the Article9 directory.

How to do it...

  1. Create a file index.html inside Recipe5 folder. In this file, define some CSS styles for elements and create a div with results ID, which will serve as a container for displaying posts from the feed.


    <html>
    <head>
    <title>Parse RSS Feed</title>
    <style type="text/css">
    body { font-family:"Trebuchet MS",verdana,arial;
    width:900px;margin:0 auto; }
    ul{ border:1px solid #000;float:left;list-style:none;
    margin:0;padding:0;width:900px; }
    li{ padding:5px;border:1px solid #000; }
    h3 { color:brown;cursor:pointer;text-decoration:none; }
    span{ font-size: 12px;font-weight:bold;}
    .content{ display:none;}
    div { width:100%;}
    a{font-weight:bold;}
    </style>
    </head>
    <body>
    <div id="results">loading
    </div>
    </body>
    </html>

  2. Before the closing &ltbody> tag, include the jquery.js file. Then send a get AJAX request to a PHP file feed.php. This file will return an XML response that will be handled by the callback function showPosts. Define the showPosts function that will parse the response XML and will create the HTML from it. The resulting HTML will be inserted inside the results DIV on the page.

    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    {
    $.get(
    'feed.php',
    {},
    showPosts
    );
    function showPosts(data)
    {
    var posts = $(data).find('channel>item');
    var str = '<ul>';
    $.each(posts, function(index, value)
    {
    var title = $(value).find('title').text();
    var link = $(value).find('link').text();
    var description = $(value).find('description').text();
    var comments =
    $(value).find('slash\\:comments').text();
    var pDate = new Date($(value).find('pubDate').text());
    var day = pDate.getDate();
    var month = parseInt(pDate.getMonth(),10) + 1;
    var year = pDate.getFullYear();
    var fullDate = day + '-' + month + '-' + year;
    str+= '<li>';
    str+= '<div>';
    str+= '<h3>' + title + '</h3>';
    str+= '<div class="content">';
    str+= '<p>';
    str+= description;
    str+= ' <a href="' + link + '" target="_blank">Read
    Full Post</a>';
    str+= '</p>';
    str+= '<span>Published on ' + fullDate + ' with '
    + comments + ' comments</span>';
    str+= '</div>';
    str+= '</div>';
    str+= '</li>';
    });
    str+= '</ul>';
    $('#results').html(str);
    $('#results ul li:even').css({'background-color':
    'CornflowerBlue'});
    }
    $('h3').live('click',function()
    {
    $(this).next('div').slideToggle('fast');
    });
    });
    </script>

  3. Now create the feed.php file. This file will get the XML for the RSS feed from a URL and will echo it to the browser.

    <?php
    $feedData = file_get_contents('http://vijayjoshi.org/feed');
    header('Content-type:text/xml;');
    echo $feedData;
    ?>

  4. Run the index.html file in the browser. You will see a loading text first. After the response is received, a list of posts will be seen initially. Clicking on a post title will expand to show its summary, publication date, and comment count. The summary will have a Read Full Post link that will open that post in a new window:

How it works...

After the DOM is ready an AJAX request is sent to the PHP file feed.php. This file gets the contents of the RSS feed from an URL using the file_get_contents function. The rss element is the root of an XML file. channel is a child of the rss node that contains information about the blog and the ten latest entries. Each entry is represented by an item node in this file. We then echo the received XML to the browser.

In jQuery, showPosts is the callback function that receives the XML in the data variable. jQuery can parse XML just like HTML elements. So to get the posts, we use the find method that gets all the item elements.

var posts = $(data).find('channel>item');

Then, we iterate over the posts variable and on each iteration we get the values for the title of post, link to the post, summary of contents, number of comments, and the publishing date. Using these variables, we create a list of items inside an unordered list. The post title is given inside an h3 element. Next is a DIV that contains the post summary, link to the post, date, and number of comments. This DIV has a class content assigned to it. The display property for content class is set to none. Therefore, only the post title will be visible when the posts are displayed.

After the list is complete we insert it inside a DIV with results ID.

We also have a click event handler function for h3 elements. Clicking on h3 elements gets the DIV next to it and toggles its display using slideToggle function. Thus, clicking the post title will show or hide its post summary. Clicking on the Read Full Post link will open the original post in a new window.

Summary

In this article we have covered:

  • Sending cross-domain requests using server proxy
  • Making cross-domain requests with jQuery
  • Creating an endless scrolling page
  • Creating a jQuery plugin
  • Displaying RSS feeds with jQuery and PHP

Further resources on this subject:


About the Author :


Vijay Joshi

Vijay Joshi is a web developer who lives in New Delhi, India, with his wife and daughter. Coming from a small town named Pithoragarh, Uttarakhand in the Himalayas, he fell in love with coding while in college and then again with PHP and JavaScript/jQuery since his early coding days. He believes that if you are passionate and enjoy your work, it becomes more of a hobby thatis not boring and never feels like a job.

After freelancing for a few years, he co-founded a web development firm called Developers Lab along with two of his friends in New Delhi where they build products for the travel industry and create custom web applications.

Vijay is also author of PHP jQuery Cookbook, published by Packt, and technical reviewer of PHP AJAX Cookbook and jQuery UI 1.8: The User Interface Library for jQuery.

When not coding, he likes to read, spend time with his family, blog occasionally at http://www.vijayjoshi.org, and dreams about getting back in shape.

Books From Packt


Drupal 7
Drupal 7

PHP 5 E-commerce Development
PHP 5 E-commerce Development

Expert PHP 5 Tools
Expert PHP 5 Tools

PHP 5 CMS Framework Development - 2nd Edition
PHP 5 CMS Framework Development - 2nd Edition

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

jQuery Plugin Development Beginner's Guide
jQuery Plugin Development Beginner's Guide

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software