Getting WordPress post titles asyncronously using Ajax…

Found in categories: Development, Javascript, PHP, Wordpress.

Getting WordPress post titles asyncronously using Ajax…

Ajax logoAssuming you already have a pretty good knowledge of JavaScript, this post should just be recap or simple enough to understand.

I know this method can also be done using the YUI framework with slightly less code but I wanted a relatively simple, raw and quick way to populate a div using Ajax to dynamically update my most recent WordPress blog posts on my homepage. I built my site before WordPress got the in thing, so i just skinned a theme and went from there. I’d previously been using a JavaScript jump list which I’d had to manually update after each post and it was tedious work. I’ll show the YUI example also later. For this simple task though, I chose 5 posts (or my page) as being an ample amount to display (later cutting that to the the most recent post) and as I’ve been dabbling with Ajax recently, I thought I’d use that method and a server side PHP module to interact with the Ajax via a GET request, communicating asyncronously on page load. For testing, I kept all the code in just one page just to make matters simple and debugging easy but naturally as I want to use an unobtrusive method and in order to remove clutter, I later removed the JavaScript into an external file of it’s own.

Here’s the HTML page div , displaying the simple static text loading, which will change to the posts themselves when they load in dynamically..

HTML

 
    <div id="info"> 
      Loading...... 
    </div> 

Nothing complicated there!.

Here’s the Ajax which includes the valuable try catch/catch construct, we use this to create the XMLHttpRequest() object instance, in this case stored in the variable request, which we can use throughout to access the object. In the example below though, I have used the JavaScript keyword ‘.this’ throughout the code in order to maybe reuse the object later if needs be. We also need to make sure whatever browser version is being used uses the correct version of the XMLHttpRequest() object type, so the try/catch construct is vital to test this. Currently there’s 3 browsers to cater for, IE5 (Microsoft created and uses the object as an ActiveXObject), IE6 (Microsoft decided to change things once again) and of course, any other browser which simply uses just XMLHttpRequest(). The code below is cross browser compliant. It’ll check each version and finally assign that to the global variable, request. I can’t imagine request usually being assigned a false value and that many people are still using browsers and versions unable to implement Ajax these days but it’s there regardless for cross compliancy. For simplicity and slightly less code, I decided to use a get method to post the request (no headers required there so less work) to post the url to the PHP script and in addition used the true parameter to ensure an asyncronous connection. You also need to remember to add the extra parameter, nocache (and a futher random parameter generated by Math.random()*1000000) as seen below to avoid the browser caching the request on subsequent visits and simply re displaying a cached page. You can alternatively prevent caching using the post method (requests aren’t cached but headers are required) if you like as it’s the same end result but you do need to remember with $_POST to use headers to let the PHP script know a post request is coming.

As we’re using XML (which is returned as an object not as a string as with responseText), you’ll need to use responseXML and use DOM methods to access the DOM tree to get the info you want once it’s returned. Incidentally responseText (used for string, number, HTML etc) and other types of textual data isn’t used here when sourcing XML, and it has a null value, so don’t forget responseXML is what you’ll need to reference for returned data not responseText.

Ajax

 
var params=encodeURI("url=mikedeveloper.com/blog/?feed=rss2"); 
var nocache="&nocache=" + Math.random()*1000000; 
var request = new ajaxRequest(); 
request.open("GET", "ajaxLabGetxml.php?" + params + nocache, true); 
var out=""; 

request.onreadystatechange=function(){
  if(this.readyState==4){ 
    if(this.status==200){
      if(this.responseXML){ 
      var title=this.responseXML.getElementsByTagName("title"); 
	
      for(var i=1;i<title .length;i++) out+= title&#91;i&#93;.childNodes&#91;0&#93;.nodeValue + "<br></title>";
      document.getElementById("info").innerHTML=out;
      }
      else document.getElementById("info").innerHTML="Sorry, Ajax returned no information";  	
    }
   else document.getElementById("info").innerHTML="Ajax error, no information supplied by the server " +
   this.statusText; 
  }
 }


function ajaxRequest()
{
  try
  {
  var request = new XMLHttpRequest();
  }
  catch(e1)
  {
    try
    {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e2)
    {
      try
      {
      request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e3)
      {
      request=false;
      }
    }
  }
  return request;
} 
	

And finally, on the server side to work with the Ajax and provide an asynchronous flow of data, I have a PHP module being posted to using the GET method and the script server side uses the associative array value ‘url’ containing my blogs RSS feed as an XML file – then fetches it courtesy of file_get_contents() function. You won’t be able to use cross domain Ajax without a PHP file!. That’s apparently considered a security risk and there are blocks preventing this practice. You’ll also need to remember to give the PHP file an XML header first, as you’re now working with XML and this header needs to be sent first before anything is output back to the Ajax.

PHP

 
    if(isset($_GET['url'])){ 
      //First outputs XML header before returning the file header("Content-type: text/xml"); 
      echo file_get_contents("http://".sanitiseVar($_GET['url']));
    }

    function sanitiseVar($link){
      htmlentities($link); 
      stripslashes($link); 
      return strip_tags($link);
    } 
    

YUI Ajax example

Alternatively, should you wish to use the YUI method and shorten your code (using the same XML setup PHP script) you need to download the framework as a .zip file. Once downloaded, go into the YUI root file and navigate down to the ‘Build folder’ where all the scripts are (read the index.html file too) and in there, you’ll need the 3 files below (.zip) to be linked at the top of your HTML file.
Alternatively, you could link directly to the Yahoo servers themselves if you wish through the YUI site as below. Just ensure you use the correct link. Below is just an example

<script src="http://yahooapis.com/2.7.0/build/yahoo/yahoo-min.js"></script>
<script src="http://yahooapis.com/2.7.0/build/yahoo/event-min.js"></script>
<script src="http://yahooapis.com/2.7.0/build/yahoo/connection-min.js"></script>

The files you need to include in your script are are..

  • yahoo-min.js
  • event-min.js
  • connection-min.js

I’ve chosen the min type JavaScript files, which are just compressed JavaScript files with whitespace and such removed to speed things up. In addition below, use the encodeURI() function to change the posted rss url to an understandable string, as that too is also being passed get parameters you’ll notice and could cause the PHP to think more parameters are being passed.

 
params = encodeURI("mikedeveloper.com/blog/?feed=rss2");
callback = { success:successHandler, failure:failureHandler }; 
request = YAHOO.util.Connect.asyncRequest("GET", "YUI_get_xml.php?url=" + params, callback); 

function successHandler(o){
  root = o.responseXML.documentElement; 
  postTitle=""; 
     
    for(var i=0; i<root .getElementsByTagName("title").length; i++) 
    postTitle += root.getElementsByTagName("title")&#91;i&#93;.childNodes&#91;0&#93;.nodeValue + "<br></root>";    
    document.getElementById("info").innerHTML=postTitle; 
}

function failureHandler(o){ 
  document.getElementById("info").innerHTML=o.status + o.statusText; 
} 

Here’s a working demo of the raw example and the YUI version. If you prefer you can separate the JavaScript from the HTML in both examples, simply put it into it’s own file and link it. The source files are downloadable from the links below

Download

Raw Ajax file | YUI Ajax source file

Leave a Reply

Your email address will not be published. Required fields are marked *