jQuery: data URLs and AJAX

Data URLs are a useful feature introduced in the web scenario during the last years. Using this feature, we can include small graphics (only up to 32 Kb in size) in our web documents. This kind of URLs have the syntax data:content-type;base64,encoded-data, where content-type is the mime type of our resource (e.g. image/gif) and encoded-data is a Base-64 encoded string containing our resource. You can use these URLs on all HTML elements that accept external content, such as a, object and, of course, img. Here's an example:

<img src="data:image/png;base64,
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />

If you enter the above data URL in the address bar of your browser and press Enter, you will actually see the image contained in such URL.

We can benefit from data URLs by using a server-side language (such as PHP) to encode our resources into Base64 and return them through AJAX so that we can use them in our web pages. First of all, we need to set up the server-side script:


$file = file_get_contents('image.gif');

$encoded = base64_encode($file);

echo $encoded;


As you can see, we used the base64_encode() function of PHP to get a Base64 encoded string containing our image. Now we can use jQuery:

  var base = 'data:image/gif;base64,';
  $('#run').click(function(e) {
      type: 'GET',
      url: 'script.php',
      data: null,
      success: function(data) {
        var url = base + data;
        $('p:first').next().attr('src', url).show();

We've first inserted a blank image into the page and then hidden it. Then we've prepared our URL that will be completed by the data fetched with AJAX. Finally, we've set the src attribute of our image to our data URL and shown the image itself. You can see a demo below.


Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.