<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Circles and Crosses &#187; REST</title>
	<atom:link href="http://ox.no/posts/tag/rest/feed" rel="self" type="application/rss+xml" />
	<link>http://ox.no</link>
	<description>Håvard Stranden&#039;s website</description>
	<lastBuildDate>Sat, 20 Aug 2011 00:11:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>AJAST &#8211; Cross-domain REST calls using JSON injection</title>
		<link>http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection</link>
		<comments>http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection#comments</comments>
		<pubDate>Mon, 24 Mar 2008 22:48:32 +0000</pubDate>
		<dc:creator>Håvard</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[AJAST]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://ox.no/posts/ajast-cross-domain-rest-calls-using-javascript-injection</guid>
		<description><![CDATA[The typical (and original AJAX) approach to calling web services asynchronously from a browser uses the XMLHTTPRequest object to request data asynchronously. However, as most of you probably already know, requests made using this object are restricted to the same &#8230; <a href="http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The typical (and original AJAX) approach to calling web services asynchronously from a browser uses the <code>XMLHTTPRequest</code> object to request data asynchronously. However, as most of you probably already know, requests made using this object are restricted to the same domain as the script they originate from. This means that in order to request data from services like Google Maps, Flickr, etc. you need to implement a server-side proxy on your domain to use the <code>XMLHTTPRequest</code> object. But what if you want to stay on the client side? Enter JSON injection.</p>

<p>JSON injection, or actually script tag injection, is a rather common technique that circumvents the <code>XMLHTTPRequest</code> limitation by dynamically injecting script tags into the calling page. A script tag can have any domain as its source, which means that cross-domain calls are possible. The technique is also referred to as JSON callbacks, although it really is not limited to JSON payloads. The technique is also referred to as JSONP, although <a href="http://ajaxian.com/archives/jsonp-json-with-padding">the original JSONP</a> is a bit more extensive than just callbacks using script injection.</p>

<p>It really is a neat technique without a cool term. JSONP is a term for a superset of JSON injection. A more precise term than JSON injection would be Javascript injection, but that&#8217;s already used to describe vulnerabilities in web pages where malicious Javascript code is injected through e.g. links from external sites. I hereby propose the term <b>AJAST</b> &#8211; <b>A</b>synchronous <b>J</b>avascript <b>A</b>nd <b>S</b>cript <b>T</b>ags. At least it&#8217;ll be the name of my implementation. If it doesn&#8217;t catch on for anything but that, we&#8217;ll even be a bit more confused than we already are. Now, what do we require to do AJAST?</p>

<h3>AJAST requirements</h3>

<p>The requirements an AJAST request lays on the server-side are the following:</p>

<ol>
<li>The server must provide its services through HTTP GET requests.</li>
<li>The client must be able to supply the name of a callback function that the response will be wrapped in.</li>
<li>The server is expected to provide a response on the form <code>callback(payload)</code>, where <code>callback</code> is the name of the callback function supplied by the client, and <code>payload</code> is the payload returned by the server. The payload can be XML, JSON, or any other form of data that the Javascript callback function can accept as a single argument.</li>
</ol>

<p>These requirements are already fulfilled by many REST services, but they are still hard to use in an AJAST fashion due to client side challenges. The two main requirements for an AJAST library are:</p>

<ol>
<li>Complete handling of requests. Nothing more than a URL and a callback should be needed to create a request.</li>
<li>Timeouts is a show stopper for AJAST. With script injection, it is difficult to know if a call completes, and from an AJAST usage perspective it is essentially impossible to create a decent solution without knowing if requests complete or not.</li>
</ol>

<p>Security is another obvious challenge, although in my view it is a challenge for the Internet in general rather than AJAST in particular. Developers creating cross-domain applications should be aware of the security risks involved, and take measures to prevent security breaches accordingly. There is no silver bullet.</p>

<p>Although several examples for implementing an AJAST request are found around the web, I found no fully functional stand-alone implementations. Dan Theurer&#8217;s <a href="http://www.theurer.cc/blog/2005/12/15/web-services-json-dump-your-proxy/">article on script requests</a> provides code that can be used to create an implementation, but leaves the timeout problem unsolved. Toolkits such as <a href="http://dojotoolkit.org">Dojo</a> also implement variations on the approach using IFrame requests, but they are a lot more hairy, and I really don&#8217;t want a framework (or parts of it) bloating the web site I am creating just to be able to do AJAST. I want a library that can perform just the task that I want it to perform, and perform it well.</p>

<h3>An AJAST library</h3>

<p>So, I decided to create my own AJAST library, <a href="http://ox.no/files/ox.ajast.js">OX.AJAST</a>, complete with the following features:</p>

<ul>
<li><b>A fully encapsulated mechanism for making AJAST calls</b><br />You simply supply a URL, the name of the callback parameter that will be appended to the URL, and a callback function.</li>
<li><b>Support for timeouts</b><br />Remote requests can of course time out, and time outs need to be handled. Apart from the obvious security challenges involved with using AJAST (note that I&#8217;m not saying they&#8217;re defects, they&#8217;re challenges for us developers to handle) , this is the hardest challenge for AJAST requests. Without the ability of specifying timeouts, we&#8217;re essentially in the dark with regards to whether or not a request will complete. OX.AJAST neatly supports timeouts by wrapping the supplied callbacks, putting on a timer, and checking for completion when the timer times out.</li>
<li><b>Guarantee that the callback function will be called</b><br />Whatever happens, and as a direct consequence of the timeout support, the library <em>guarantees</em> that the callback function will be called. For this reason, the callback function must accept two arguments, the first a boolean indicating if the request succeeded or not, the other a string containing the response from the call. If the first argument is false, the call may have timed out or failed.</li>
</ul>

<h3>Using the AJAST call function</h3>

<p>There are two ways of using OX.AJAST. The simplest is to use the <code>call</code> function.</p>

<p><pre class="brush: javascript; ">
  // Create a function that will be called when the AJAST request completes
  function callCompleted(success, data)
  {
    if(!success)
      alert(&#039;Fail&#039;);
    else
      alert(&#039;Received: &#039; + data);
  }
  // Call a service
  OX.AJAST.call(
    &#039;http://xampl.com/rest?arg=foo&#039;, 
    &#039;callback&#039;, 
    callCompleted);
</pre></p>

<p>The <code>call</code> function will execute the request by appending <code>&amp;callback=wrapper</code> to the URL and injecting a <code>&lt;script&gt;</code> tag with the final URL as the <code>src</code> attribute. This will add a call to the DOM as soon as the data is received, which the browser will execute.</p>

<p>The function called from the injected script tag is a wrapper around the <code>callCompleted</code> function provided to the <code>call</code> function. The wrapper function is created by the <code>call</code> function, and handles timeouts and deletion of the script tag after the <code>callCompleted</code> function completes. As mentioned, by using this wrapper, the AJAST library can guarantee that <code>callCompleted</code> will be called, which significantly eases the handling of asynchronous calls for users of the library.</p>

<p>The function also allows you to specify how long the request will wait for a response before it times out. The default timeout is 5 seconds. Finally, you can pass an argument specifying if you want the response to be automatically decoded from JSON before it is passed to your callback function.</p>

<p><pre class="brush: javascript; ">
// Call with a 10 second timeout, decode JSON response
OX.AJAST.call(
  &#039;http://xampl.com/rest?arg=foo&#039;, 
  &#039;callback&#039;, 
  callCompleted, 
  10000, 
  true);
</pre></p>

<p>As stated above, all callback functions must be on the form <code>callbackfunction(success, data){}</code>, where <code>success</code> indicates whether or not the asynchronous call succeeded, and <code>data</code> is any data that was received from the call. It is also important to note that <code>data</code> may be undefined, but <code>success</code> will always be <code>true</code> or <code>false</code>.</p>

<h3>Using the AJAST broker</h3>

<p>The AJAST broker encapsulates a common pattern for REST requests using HTTP GET. Many RESTful services found online typically use some kind of root URL of the form <code>http://xampl.com/rest</code> as the base URL for all their REST services. The query string determines which service is requested, as well as the arguments for the service.</p>

<p>For the services that follow this pattern, the AJAST library provides a <code>Broker</code> class that encapsulates the process of calling the REST services.</p>

<p>The example below shows how the request from the first example can be made using the broker.
<pre class="brush: javascript; ">
// Create a broker object
var broker = new OX.AJAST.Broker(
  &#039;http://xampl.com/rest&#039;, 
  &#039;callback&#039;
);
// Perform the same call using the broker
broker.call({arg: &#039;foo&#039;}, callCompleted);
</pre></p>

<p>The broker also supports the specification of a timeout limit, automated JSON decoding, and also provides the option of passing a set of default arguments that will be passed with every request, such as a Flickr API key.</p>

<p><pre class="brush: javascript; ">
// Create a broker object
var broker = new OX.AJAST.Broker(
  &#039;http://xampl.com/rest&#039;, 
  &#039;callback&#039;, 
  true, // Decode JSON response
  10000, // Timeout in ms
  {APIKey : &#039;123&#039;} // Default parameters
);
</pre></p>

<p>Now let&#8217;s do something useful with it.</p>

<h3>A real example: Flickr using AJAST</h3>

<p>To keep the example as simple as possible, we&#8217;ll create the functions necessary for a page which fetches the most recent photos from <a href="http://flickr.com">Flickr</a>.</p>

<p>Luckily, Flickr supports REST and JSON callbacks in a lovely manner, so we&#8217;ll use the broker for our calls.</p>

<p><pre class="brush: javascript; ">
function flickrGetRecent()
{
  // Create  a broker
  var broker = new OX.AJAST.Broker(
    &#039;http://api.flickr.com/services/rest/&#039;, 
    &#039;jsoncallback&#039;, 
    true, 
    10000,
    {api_key: &#039;YourVeryOwnFlickrApiKey&#039;, 
      format: &#039;json&#039;});&lt;/p&gt;

&lt;p&gt;// Perform the call
  broker.call(
    {method: &#039;flickr.photos.getRecent&#039;}, 
    recentFetched);
}

</pre></p>

<p>We&#8217;ve told the broker to call a function named <code>recentFetched</code> when the recent photos have been fetched, so let&#8217;s implement that as well. To keep the example simple, we&#8217;ll just append the photos to the body of the document.</p>

<p><pre class="brush: javascript; ">
function recentFetched(success, rsp)
{
  // Check for failure
  if(!success || !rsp || rsp.stat != &#039;ok&#039;)
  {
    alert(&#039;Call failed&#039;);
    return;
  }&lt;/p&gt;

&lt;p&gt;// For each photo...&lt;br /&gt;
  for(i in rsp.photos.photo)
  {
    photo = rsp.photos.photo[i];&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Create an img element
img = document.createElement(&#039;img&#039;);

// Set its source to a valid Flickr URL
img.setAttribute(&#039;src&#039;, 
  &#039;http://farm&#039; + (photo.farm || 1) + 
  &#039;.static.flickr.com/&#039; + photo.server + 
  &#039;/&#039; + photo.id + &#039;_&#039; + photo.secret + &#039;_t.jpg&#039;);

// Append the element
document.body.appendChild(img);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;}
}
</pre></p>

<p>Now we just have to call flickrGetRecent from somewhere in a document, and the most recent photos will be appended to the document. A full example can be seen <a href="http://ox.no/files/flickr.html">here</a>. Note that you will need a <a href="http://www.flickr.com/services/api/">Flickr API key</a> to test it.</p>

<p>As you can see, the OX.AJAST library is really easy to use, and enables you to do pure client-side REST service calls across domain boundaries with hardly any effort. I hope you find it useful. Drop a comment if you have problems or suggestions, or if you create improvements to it. Now <a href="http://ox.no/files/ox.ajast.js" title="The OX AJAST library">start using AJAST</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://ox.no/posts/ajast-cross-domain-rest-calls-using-json-injection/feed</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss>

