Build an Image Uploader with Imgur API and JavaScript

If you are building a file uploader app that would allow users to upload images from the local disk to the web, Imgur is a good platform to start with. FileStack, Cloudinary and UploadCare are some popular web services that offer simple file upload widgets but the Imgur API is free for non-commercial usage or if your app is open source.

Go to, register your application and generate the client ID. All HTTP requests for uploading images to Imgur must include the client_id in the authorization header and this would also let you upload images anonymously without the image being tied to your personal Imgur account.

In the HTML section of your website, include an <input> field of type file and set the accept attribute to “image/*” so that file selector window would only allow selection of image files. We’ll also add a data attribute (max-size) to reject files that are bigger than a specific size (in Kb).

Next, we use jQuery to attach an onChange event handler to the input field that gets triggered when the user clicks the input field and selects a file.

$("document").ready(function() {

  $('input[type=file]').on("change", function() {

    var $files = $(this).get(0).files;

    if ($files.length) {

      // Reject big files
      if ($files[0].size > $(this).data("max-size") * 1024) {
        console.log("Please select a smaller file");
        return false;

      // Begin file upload
      console.log("Uploading file to Imgur..");

      // Replace ctrlq with your own API key
      var apiUrl = '';
      var apiKey = 'ctrlq';

      var settings = {
        async: false,
        crossDomain: true,
        processData: false,
        contentType: false,
        type: 'POST',
        url: apiUrl,
        headers: {
          Authorization: 'Client-ID ' + apiKey,
          Accept: 'application/json'
        mimeType: 'multipart/form-data'

      var formData = new FormData();
      formData.append("image", $files[0]); = formData;

      // Response contains stringified JSON
      // Image URL available at
      $.ajax(settings).done(function(response) {


The onChange handler makes as synchronous AJAX file upload request to the Imgur API with the image file sent inside the FormData object.

The form’s encoding type is set to multipart/form-data and thus the sent data is in the same format as the form’s submit method.

After the image is upload, Imgur returns a JSON response containing the public URL of the uploaded image and the deletehash that can be used to delete the file from the Imgur servers.


Make AJAX Request to Google Script Web App with jQuery

You have published a Google Apps Script as a public web app that returns data as JSON but when you try to make an AJAX call to this web app using jQuery, you get the “Cross Origin” error.

Your AJAX request is blocked by the browser because of the “same origin policy” that disallows reading the remote resource at An easy workaround to this problem is JSONP or JSON with a prefix. With JSONP, the client’s browser won’t enforce the same origin policy but for that to work, you would need to modify your Google Script web app to return results in JSONP format.

Here’s an example web app that return JSONP results.

function doGet(e) {
  var result = "";
  try {
    result = "Hello " +;
  } catch (f) {
    result = "Error: " + f.toString();
  result = JSON.stringify({
    "result": result
  return ContentService
  .createTextOutput(e.parameter.callback + "(" + result + ")")


The MimeType of the output is set as JAVASCRIPT and that will return as JSONP. You can now call this web app from your client side JavaScript as shown here.


Get Google Spreadsheets Data as JSON in your Website

You can retrieve the content of any public Google Spreadsheet in your web app using JSON feeds. The sharing permissions of the Google Spreadsheet should be either “Public” or set to “Anyone with link can view” for the app to fetch cells from the Google Spreadsheet without authentication.

You will also need to publish the sheet (File -> Publish to the web -> Publish) for the data to be accessible from your website or REST powered web app.

The JSON and XML feeds for any Google Spreadsheet is available at:

JSON Format:

XML Format:

Here’s a sample jQuery based example that pulls data from a public spreadsheet in Google Drive as JSON and prints as HTML. This can be clubbed with IFTTT or Zapier for more useful integrations.


Scrape Twitter Data with JavaScript

You can use YQL and JavaScript to quickly scrape tweets from Twitter search results on the client side. The tweets are returned as JSON that can be easily parsed using regular expressions.

The advantage with this approach is that it requires no OAuth (authorization) and even old tweets can be returned when the search request is combined with the since: and until: search operators.

YQL allows 2000 requests / per hour / per IP so you are also unlikely to hit the usage limit.

function fetchTweets(q) {

  var yql  = "*%20from%20json%20where%20url%3D%22";
  var base = "";

  // Test the URL in YQL console to make sure it works
  var url  = yql + base + encodeURIComponent(q) + "%22&format=json";

   // Make synchronous AJAX request to yql
  var tweets = jQuery.ajax({type: "GET", url: url, dataType: 'json', async: false }).responseText;

  // Parse the JSON response
  var data = JSON.parse(tweets);

  // Return the HTML search results
  return data.query.results.json.items_html;


Find People’s Location through Google Maps

The Where Am I and Postal Address apps using the HTML5 Geolocation service and Google Maps’ Geocoder service to determine your accurate physical location up to the zip code.

The HTML5 geolocation service returns the current longitude and latitude coordinates which are then passed to Google Geocoder for determining the actual geographic location including the street address and the pin code.

This can be used by shopping websites to serve store results that are nearest to the visitor’s current location, by banks for showing the location of nearest ATMs, gas stations and so on.

HTML – We are including the jQuery library and the Google Maps API for geocoding the location.

    Where Am I
Postal Address
Zip Code

When the user click the Where Am I link, the browser ask for permissions to share his or her location with the website. If they say Allow, the co-ordinates are passed to the Google Maps API for determining the physical address.

$(function () {
    $("#showMyLocation").click(function (event) {
        $(this).html('Determining address...');
        navigator.geolocation.getCurrentPosition(function (position) {
            var geocoder = new google.maps.Geocoder();
            var latLng   = new google.maps.LatLng( 
                position.coords.latitude, position.coords.longitude);
                'latLng': latLng
            }, function (results, status) {
                for (var i = 0; i < results[0].address_components.length; i++) {
                    var address = results[0].address_components[i];
                    if (address.types[0] == "postal_code") {
        return false;

Create HTML Elements with JavaScript

You can create HTML elements directly with JavaScript /jQuery and also assign data attributes, CSS style, click handlers, classes and IDs to these elements through chaining.

Here’s an example.

var fox = $("
") .css("background", "lightyellow") .css("padding", "15px") .html("What did the fox do?") .data("color", "brown") .addClass("fox") .attr("id", "quick") .click(function () { alert("It jumped over the lazy dog!"); console.log($(this).data()); }) .append($("
")) .append( $("").html("click for the answer")); $("body").append(fox);

Turn an Entire DIV into a Clickable Link

If you have been to a Pinterest like site that uses the grid masonry style layout, you may have noticed that one can hover over any region inside the box and its clickable.

A typical DIV is written using the following markup

Box Title

The Quick Brown Fox Jumped Over The Lazy Dog

Webpage URL

There’s a outer DIV and it has elements like the title, description and a link. The requirement is that when someone hovers their mouse over the DIV, it should point to the hyperlink that’s contained inside the DIV.

This can be done in two ways – using CSS or using jQuery.

The CSS approach – Make the Whole DIV clickable