Tag Archives: jQuery

Access Remote XML via jQuery+AJAX with PHP as a Proxy

If you’ve ever had to work with XML from another domain, and only had JavaScript in your toolbox, you can feel my pain. Cross-domain XML has been the bane of my existence for many years now, when working on sites where there is no server-side scripting language available. jQuery has some great AJAX features, but you can’t make use of any of them if the file you’re trying to retrieve is an XML file on another domain. Until now. PHP is still required as part of this equation, but it acts as a web service, rather than residing on the server where your site lives.

Setting Up PHP as a Web Service

Thanks to a few new JSON functions added in PHP 5.2, we can build an XML to JSON web service in 4 lines of code. That’s right, 4 lines. Here it is, in all its glory:

$c = $_GET['car'];
$s = file_get_contents('http://www.example.com/' . $c . '.xml');
$a = json_decode(json_encode((array) simplexml_load_string($s)),1);
echo $_GET['callback'] . '(' . json_encode($a) . ');';

This code would reside on a server separate from the server where your site is hosted. And now the break down:

$c = $_GET['car'];

Get the value from the query string (browser’s url bar) with the name “car”, which we’ll see when we build the jQuery request, and save it in a variable named “$c”. Easy enough.

$s = file_get_contents('http://www.example.com/' . $c . '.xml');

Get the contents of a remote XML file, inserting the $car variable in the URL, and save in a variable named “$s” (for “string”).

$a = json_decode(json_encode((array) simplexml_load_string($s)),1);

Convert the XML string into a JavaScript array using PHP’s new json_decode and json_encode functions, and save this new array in a variable titled “$a”.

echo $_GET['callback'] . '(' . json_encode($a) . ');';

Here’s where the magic happens. We take that array, and convert it into JSON using PHP’s json_encode function. We also get the “callback” variable from the query string, which is required by jQuery, and append parentheses around the encoded JSON. The appended parentheses are also known as the “P” in JSONP, or “JSON with Padding”. What this does is essentially create a JavaScript function to pass back to your site that looks like this:


Setting Up jQuery to Call Your Web Service

Once you’ve got your PHP web service setup to convert XML to JSON, making the request in jQuery is pretty simple as well. Here’s how its done:

$(document).ready(function() {
		dataType: 'json',
	  	url: 'http://www.example2.com/my-web-service.php?car=mercedes&callback=?',
		success: function(data) {
			//parse your new JSON object here

This is a pretty standard jQuery AJAX request. The url paramater is the most important piece here. We’re looking for the JSON data on our server where our PHP service is hosted, and passing 2 variables:

  • car with a value of mercedes, and
  • callback with a value of ?

The variable of car=mercedes depends on the site where you’re pulling your XML from. This isn’t required, it just demonstrates how you could build a flexible web service to leverage for more than one external XML feed. The second variable callback=? is required by jQuery. The question mark is just there to append an additional name/value pair. jQuery will recognize the variable callback=? and replace the question mark with a randomly generated string of numbers. That’s why in your PHP web service, you get the callback variable, and send it back to jQuery as the function name. Its a sort of security measure.

That’s really it; from this point you have a jQuery object to work with containing all the data in the original XML file. You can see the jQuery object and all its pieces easily by setting a few breakpoints in Firebug and digging in.

If you want to get into the gritty details of how this works, like the coolness of how you can call functions in JavaScript by passing JSON as the argument, and how PHP can convert XML to an array and then to JSON, check out a few of the articles I referenced while building this:

Its like rejuvenation

I couldn’t resist the temptation to blatantly quote Howard Stern whack packer Blue Iris, as the phrase describes my recent adventures in web design perfectly. It had been way too long; way too long since I’d put myself back in student mode, way too long since I’d let HTML 5 and CSS 3 take shape without paying too much attention, and way too long since I’d posted here. So without further ado, lets take a look at what’s happened in web design over the past six months:

  1. Zeldman released Designing with Web Standards, 3rd Edition.
  2. HTML 5 and CSS 3 support gain traction.
  3. WordPress 3 set to drop any day now.
  4. The BIG Web Show launched.
  5. jQuery still rocks.

Lets take them one at a time:

1. Zeldman has released Designing with Web Standards, 3rd Edition.

The king is back. And this time he’s got a sidekick. That’s right, Jeffrey Zeldman released the 3rd edition of the book that changed the web industry, and he signed up Ethan Marcotte as his trusty co-author this time around. I just blazed through the book in a week, and I’m gearing up for a second run-through. Needless to say, not only will this book give you a rock-solid foundation for building modern web sites, its been updated with current technologies in mind, including new kids on the block, HTML 5 and CSS 3. Also, a special treat this time around is a companion volume, Developing with Web Standards, released simultaneously. Author John Alsopp picks up where Zeldman leaves off, providing the practical solutions to Zeldman’s powerful theory. I’m giving myself a bit of time to digest Designing with Web Standards prior to diving into Developing, but look for a full review of Designing to come over the next few weeks here at Withinsight. All I can say for now is, bravo.

2. HTML 5 and CSS 3 support gaining traction.

HTML 5 and CSS 3 not only offer all kinds of fun new goodies for web designers and developers alike, they’re now starting to gain real support. In addition to the support already provided for new HTML elements and CSS properties in browsers where you’d expect it like Firefox, Chrome and Safari, it appears that IE9 has completely jumped on the bleeding-edge standards wagon. While the finalized specs are still years off, if all major browsers support them with the release of the next version of IE, we’ll be able to start using them reliably very soon. Actually, you already can, but more on that in bullet 4. If IE9 really does support HTML 5 and CSS 3 as well or better than other modern browsers, this may just be the kick that IT departments and large corporations need to drop their “IE6 fo’ life” mantra. Exciting times indeed.

3. WordPress 3 is set to drop any day now.

WordPress 3 will support multi-site installations, meaning you can install WordPress once and create multiple blogs from the single installation. I’m so happy I think I just made a mess in my pants. This means no more upgrading multiple installations of WordPress with each release, centralized plugin management, and huge swaths of citizens rejoicing in the streets for weeks on end. Well, maybe not that last part, but this one feature alone would be enough for me for one upgrade. I’ve played with the beta 2 release a bit, and its super-simple to setup multiple blogs, and basically acts like WPMU did, where you can select subdomains or subdirectories for all your additional blogs. The potential is making me dizzy. Roo-haa.

4. The BIG Web Show launched.

Zeldman’s The BIG Web Show launched recently, and just concluded its third episode this past Thursday. If you like web design, pay attention. Episode 2 featured Jeremy Keith as a special guest, promoting his latest book, HTML 5 for Web Designers, which is slated to drop in June. Remember when I mentioned using HTML 5 and CSS 3 now above? Good! In The BIG Web Show, episode 2, Keith explains how you can start supporting the semantics of HTML 5 now by using standard class names for your divs that correspond to the HTML 5 elements. Not only does it make transitioning in a future redesign easier, it makes explaining your classes to other designers or developers 100 times easier when you hand off your work because you can just point them to the spec. Fantastic. Also, kind of a sub-bullet here, HTML 5 for Web Designers is the first book from A Book Apart publishing! I’m overjoyed with this new publishing company and will likely gobble up each and every offering they proffer from here until infinity.

5. jQuery still rocks.

I really only started working with jQuery personally about a year ago, and since then the library has really gone full-blown as the hands-down most popular JavaScript library in existence. Not only has it been included in the download of WordPress for a while now, its hosted by Google in its compressed form, which means if you link to the Google version and your site visitors already visited a site that also links to the Google version of jQuery, they don’t have to download it again. In addition, all the JavaScript examples in Designing with Web Standards, 3rd Edition are in jQuery, because it just makes JavaScript so much more concise and is easy for the uninitiated to pick up, having a syntax very similar to CSS selectors.

So that’s it for now, stay tuned for more frequent updates as I’m completely turned on by the impending release of WordPress 3 and impending web standards developments. This truly is an exciting time to be a web developer. Cheers!

SXSW and jQuery

So right about now I’m wishing that if I could be anywhere, it would be at SXSW (South by Southwest).  For those of you who don’t know, its about the coolest festival on the planet.  And I don’t know from experience, just from colleagues and coworkers and podcasts and industry moguls giving me an earful.

In addition to being a hotspot for web design, SXSW boasts an impressive musical lineup each year, and this year I’ll be disappointed that I’ve missed The Everyday Visuals, Madi Diaz, and the undisputable heavyweight of soul, Miss Erykah Badu.

I’ve been hearing about it for weeks, from Paul Boag blabbering about it on his Boagworld podcast, to having to postpone projects with colleagues who are attending, to CSS guru Eric Meyer tweeting, “If you’re not going to SXSW, tweet like you’re there.  Nobody will know the difference.”  Yeah, that almost makes up for not being able to attend.

But alas, I am not one to linger, and the time spent here at home has given me the opportunity to start exploring jQuery, which was recommended to me by Alex King, famed author of the WordPress Popularity Contest plugin, and another item that Paul Boag has been going on endlessly about for months now.  I finally broke down and downloaded the library and started playing with it.

From my first impressions, Paul has reason to be going on endlessly.  It seems that the potential of what a web designer or developer can accomplish with the JavaScript library is in fact endless.  The first item that caught my eye was the fact that on the jQuery homepage they offer the expanded, developer version of the library, along with the compressed, production version.  I was immediately reminded of the hours I’ve spent testing the best method to minify, compress and serve my Prototype and Scriptaculous libraries.  jQuery does this for me?  Fantastic.

Second, I was really impressed with the quality and quantity of documentation.  Compared to Prototype, jQuery blows it out of the water in terms of a working online manual.  I think I’ve officially moved the “Prototype and script.aculo.us” book to the back of my “must read” list.  I’ve actually read the first half of it already, but it was cryptic and would have required re-reading on my part to fully absorb the material.  jQuery is the complete opposite.  There are video tutorials explaning the beginner steps.  Video tutorials.

The last thing about jQuery that really hooked me was the ease with which a web designer can pick up the library.  A lot of the arguments you pass to the library are the same as in CSS.  So if you’re looking for a div with the id of conference, you pass (“#conference”) as the argument.

It seems like its going to be really easy to quickly get up to speed with the library, and that it has a lot of power in terms of what you can do with it.  If you’re interested, check out the jQuery site, the jQuery UI site, as well as some of the video tutorials. Really, really, really cool stuff.