Category Archives: JavaScript

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:

callback987986215(allyourJSONdata)

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() {
	$.ajax({
		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:

Advertisement

Review: Simply JavaScript by Kevin Yank and Cameron Adams

Book review of Simply JavaScript by Kevin Yank and Cameron Adams

Simply JavaScript by Kevin Yank and Cameron AdamsI read Simply JavaScript a few months back, and couldn’t help but include it in my reviews here at withinsight.com.  Its simply too good not to.  I’ve got a decent amount of JavaScript experience, although not necessarily through practice.  JavaScript has always been that part of my web design arsenal that I’ve wanted desperately to add, but has never seemed to work its way into regular usage in my day-to-day work.  You can’t say its for lack of trying, as I’ve read the first half of O’Reilly’s JavaScript, The Definitive Guide, which while full of great info, is not necessarily the best introduction to JavaScript for the beginning scripter.  I then found DOM Scripting by Jeremy Keith, which offers a very, very introductory level explanation of JavaScript before digging into the basics of DOM Scripting.  I had a decent picture of what else was out there in terms of JavaScript books.

Jeremy Keith is actually the one who recommended Simply JavaScript on his website a while back, which is how I originally heard about it.  He stated that his book DOM Scripting was intended for a very specific audience, and that there really weren’t any other books that did it as well as he does, until Simply JavaScript was released.  Very big of an author to acknowledge the competition with a tip of the hat.

Meet Your New Friend, JavaScript

If I could, I would probably go back and start from scratch originally with Simply JavaScript.  It is a perfect introduction for the web designer looking fill out the third leg of the XHTML/CSS/JS stool that we all sit upon.  Yank and Adams present the material in a way that anyone with a little XHTML and CSS experience will not only understand, but really find themselves enjoying.  I literally found myself laughing out loud at a few points, such as:

The popularity of regular expressions has everything to do with how useful they are, and absolutely nothing to do with how easy they are to use – they’re not easy at all. In fact, to most people who encounter them for the first time, regular expressions look like something that might eventuate if you fell asleep with your face on the keyboard.

Fantastic!  There are a number of moments like this that brighten up the pages.

Simply JavaScript is written in a progressive tutorial format, so you can move through it chapter by chapter, rather than using it as a reference.  The one exception to this is the chapter on “Errors and Debugging” which falls fairly late in the book.  I was okay without it for the first few chapters, but once I got into chapters 4, 5 and 6 on events, animation, and form enhancements, respectively, I think I could have done with reading that chapter first.  In chapter 7, they introduce the Firebug Firefox extension, and how to use it to pause the state of JavaScript at selected lines in your code, which I definitely could have used a little earlier in the book while troubleshooting projects.

JavaScript Libraries Galore

Another great aspect of Simply JavaScript is how they relate the tutorials completed in each chapter to the respective current JavaScript library.  So if you’ve heard about all the cool stuff web designers and developers have been doing with libraries like Prototype & script.aculo.us, MooTools, Dojo, jQuery, or Yahoo’s YUI, but haven’t been able to find practical uses for any of them in your projects, here’s where you can make the connection.

Yank & Adams build a very nice core library that you can use to power a few solutions to design problems that have faced web designers for years, like building stripey tables on the fly, or validating form information.  They even get into more advanced topics like animation and AJAX.  Actually, after you read this book, you’ll probably realize how non-advanced these topics are.  This book truly does make JavaScript simple!

I feel like a lot of JavaScript is like a catch-22 in that until you read a book like this, you have a very limited arsenal.  You may know how to pop open a new window or change the behavior of a few links, but you don’t truly have a grasp of the potential of what you can accomplish with JavaScript.  Reading a book like Simply JavaScript, even if you don’t go into all the details and grasp every last concept, at a bare minimum lets you know what you can do, which will help you tremendously in future projects.

First Impressions Make Such an Impact

One last thing that I need to mention is the production quality of this book. Sitepoint really went all out.  I’ve got six Sitepoint books, everything from HTML basics to PHP, and Simply JavaScript is the only one that is full color. In addition to brightening up the pages with color, the footnotes are all located at the bottom of each page.  I was recently reading the O’Reilly book AJAX Design Patterns, and found it extremely annoying to have to continually skip over URLs in the middle of the text.  Sitepoint places URL footnotes where they should be, at the foot of each page, making it easier to concentrate on the text and code, and reference the footnotes when you want to.

Overall, this is absolutely the best starting point for the beginner JavaScript student, and I would recommend it to any web professional who works with code on a daily basis.  It will teach you to apply the same unobtrusive principles that you hopefully already apply of CSS to XHTML documents, instructing you how to do the same with JavaScript.

You can purchase Simply JavaScript over at Amazon.com.

Rating

  • Overall: 9 out of 10

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.