Paulund
2012-02-23 #jquery

How To Use The jQuery Load Method

In today's tutorial we are going to learn how to create a small web application that will display an RSS feed on a web page using jQuery and PHP. To do this we are going to use jQuery AJAX functionality to easily get the data from a PHP proxy and display it on the web page.

jQuery Ajax Load Method

In this tutorial we are going to use the jQuery load method which is a quick way of using the AJAX Get function to get the contents of a file. The load method will then run automatically every minute to new data from the PHP page. This method takes 3 parameters, url, data and callback function.


.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )

  • URL - The URL to which the request is sent.
  • Data - A string that is sent to the URL as parameters to use.
  • Callback Function - A function that will run when the request is complete.

The HTML

The HTML for this is simple we are just going to have a div which we are going to populate with the return from the jQuery AJAX functionality.


<div id="feed_result"></div>

The PHP

The PHP we are going to create is a small PHP class that will get a URL as a constructor parameter to store in a class property. Then we can call the GetFeed() method to which will make a cURL request to get the contents of the RSS feed. We can then loop through the contents of the RSS feed to create divs for the content. Once we have the contents for the divs all we have to do is echo the contents and it will be displayed on the page. As we are using the jQuery load method we can just call this PHP file and it will display the contents of the PHP file.


<?php

// Create new object and pass in RSS feed URL
$process = new Process_Rss_Feed("http://feeds.feedburner.com/Paulundcouk");

// Call GetFeed Method
$process->GetFeed();
    
class Process_Rss_Feed{
	
	private $url = false;
	
	/**
	 * Constructor of the Process RSS Feed class
	 * @param url - URL to get Feed
	 */
	public function __construct($url){
		$this->url = $url;
	}
	
	/**
	 * Get rss feed
	 */
	public function GetFeed(){  
		//Initialize the Curl  
		$ch = curl_init();  
		  
		//Set curl to return the data instead of printing it to the browser.  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2); 
		  
		//Set the URL  
		curl_setopt($ch, CURLOPT_URL, $this->url);  
		  
		//Execute the fetch  
		$data = curl_exec($ch);  
		  
		//Close the connection  
		curl_close($ch);
		
		// If data is returned
		if($data != null){
			// Create XML object
			$xml = new SimpleXMLElement($data);
			
			$result = "";
			
			// Loop through each of the items and dislay the title and the description
			foreach($xml->channel->item as $item){
								
				$result .= '<div class="item">';
				
					$result .= '<h2>'.(string)$item->title.'</h2>';
					
					$result .= '<p>'.(string)$item->description.'</p>';
					
				$result .= '</div>';	
			}
			
			echo $result;
		}  
	}
}

?>

The jQuery

The jQuery we are using for this application is below. There is a document ready function which runs when the jQuery file is load this is where we will do all the main work for the application. First we start off by setting up the ajax functionality, all we are going to do here is say on all ajax calls before you send the request hide the feed_result div and then when the request is finished we want to display the feed_result div. Next we set-up a jQuery object for the feed_result div, this is the object we are calling the load method on. The load method will then call the process_rss_feed.php file which will send an ajax GET request to the contents of the PHP file and will load the contents in the feed_result div. Now we can add the functionality to auto refresh the content in the div, by calling the setInterval after one minute.


(function($)
{
	/**
	 * Run this function on ready of the document
	 */
    $(document).ready(function()
    {
    	SetupAjax();
    	
        // Create feed result object
        var $result = $("#feed_result");
        
        // Load the contents of the URL in the result object
        $result.load("process_rss_feed.php");
        
        // Setup an auto refresh function to run every 30 seconds
        var auto_refresh = setInterval(function()
        {
            $result.load('process_rss_feed.php');
        }, 60000);
    });
    
    /**
     * Setup the ajax functionality
     */
    function SetupAjax(){
    	$.ajaxSetup(
        {
            beforeSend: function() {
                $('#feed_result').hide();
            },
            success: function() {
                $('#feed_result').show();
            }
        });
    }
    
})(jQuery);

That's It!

That's all it takes to get the jQuery load method working on a small web application to display the contents of an RSS feed on a web page.