Using XMLHttp to make calls with a proxy

Product
Video Cloud
Applies to Roles
Developer
Version
Brightcove 5
Modules
Media API
Edition
All

This document provides an overview of how to use XMLHttp from JavaScript to call the Media API via a server-side proxy. Using the XMLHttp object in JavaScript to make calls to the Media API means you don't have to reload the page in order to get more data from the server. Rather, you can make an "inline" request and update only the parts of the current page that you want to change. This method provides the flexibility of JavaScript and AJAX-type interactivity with the security of server-side code. However, it doesn't provide SEO benefits because it relies on JavaScript on the page to retrieve data.

Here are a couple primers to review if this sounds interesting:

Handling cross-domain security

In pursuing this approach, you need to watch out for, though: cross-domain security. Browsers restrict code from making requests to another domain that could occur without the user's knowledge. If they didn't, malicious scripts could send personal data to malicious web sites.

Browsers handle this in different ways. Internet Explorer, for example, prompts the user to acknowledge that a request is being made. Firefox, however, doesn't prompt at all – the request always fails. Because you can't count on a particular behavior across browsers, you need to employ another method to circumvent the restriction on cross-domain requests. Read Jason Levitt's article at XML.com, which describes the three widely-accepted methods for making cross-domain requests:

  • using dynamic script tags
  • using a server-side proxy, as described in this document
  • configuring your web server to auto-proxy requests

Of the three, we've documented how two of them can be done with the Media API. The third — configuring your web server to auto-proxy requests — is too dependent on what web server you use to document effectively.

Server proxy example code

Click here and View > Source to see the JavaScript code for this how-to (note: it's not functional without the server proxy).

Identify your HTTP requests

To make a request to the Media API, you first need to determine the URL and parameters you'll use for a request. For example, to retrieve the name and id fields for all the videos in your library, your request would look like this:

http://api.brightcove.com/services/library?command=find_all_videos
  &token=0Z2dtxTdJAxtbZ-d0U7Bhio2V1Rhr5Iafl5FFtDPY8E.&random=8918
  &video_fields=id,name,refId
/* (Just replace the token with yours to have it search your library) */

But because we will be using a proxy, we won't make our request from the page to this URL. The request will first go to the proxy. The proxy URL is completely up to you and your server, but for the sake of example, we'll assume the proxy URL and request will look like this:

http://www.yourdomain.com/php_proxy_simple.php?command=find_all_videos&random=8918&fields=id,name,refId

Note the params are the same, just the URL is different. Also note we've left out the token. For security's sake, we can append the token on the server before making the call.

Now let's look at the contents of the proxy script.

Create a web proxy

You can create a proxy in any server-side language that can make HTTP request; the principles will be the same. You can also use one of the many open-source scripts that are on the web in just about every language. Here are some references:

  • For Java, Greg Murray's approach to building a proxy is the de facto standard. Greg also has a LOT of advice for the Java developer looking to write AJAX apps.
  • For PHP, there are many more options. Yahoo has created a Simple Web Proxy for their web services that will work just as well for the Video Cloud API. But a quick Google search will turn up a variety of additional options.

You can also choose to write your own. The script will need to process synchronously: when requested it will first make the request to the Media API and wait for the response before sending its own response back to the page. Here's what your script will need to do:

  1. Parse the incoming request to separate the URL from the parameters
  2. Assemble a new request with the URL to the Media API plus the parameters
  3. Make the request
  4. Pass the API response as its own response

Write the XMLHttp Request

The final piece is the in-page JavaScript that initiates the request. First we need to instantiate the XMLHttp object that brokers the server call:

/* Pretty standard stuff, cross-browser compatibility */
 
var xmlhttp = null;
if (window.XMLHttpRequest) {
  xmlhttp = new XMLHttpRequest();
  if ( typeof xmlhttp.overrideMimeType != 'undefined') {
    xmlhttp.overrideMimeType('text/xml');
  }
} else if (window.ActiveXObject) {
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  alert('Perhaps your browser does not support xmlhttprequests?');
}

With the object instantiated, making the request is a couple of additional method calls:

xmlhttp.open('GET', url, true);
xmlhttp.send(null);

The url variable should be the request to the proxy we identified earlier. If you want to invoke this on a button click, wrap it in a function and use the onclick parameter of your button to tie it all together.

Handle the XMLHttp Response

The next piece is the callback, which handles the response from the server, hopefully with our data!

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    // do something with the results
  } else {
    // wait for the call to complete
  }
};

Here we're waiting for the readyState property to equal "4" and the HTTP status code to be "200". These two together means the request completed successfully. There are many other combinations, however, for various errors and responses. A well-built application will handle various errors gracefully. The above example is simplified and will just fail silently.

Parse the results

This part is the easiest: the Media API returns JSON, which is native JavaScript objects in string form. To convert them back to JavaScript objects, simply "eval" them:

var myData = eval( "(" + request.responseText + ")" ); 
/* Wrap the response in parens to ensure it's eval'd as an 
   expression and not a function */

Note that eval turns data to objects and runs any code without checking for anything that may be undesirable. The Media API returns the contents of the fields in your database, which may or may not contain JavaScript code — we don't check. It's worth investigating using a JSON parser that can safely distinguish between code and data.

With myData in hand, you can work with the response as a native object and insert data into your UI with DOM methods like innerHTML.

Tags
proxy