Our Blog

Latest news and updates from BinaryOps.io

Using a BinaryOps API with jQuery

Another quick and easy way to use the BinaryOps API is with the ajax functions in jQuery. By adding a little bit of JavaScript to an otherwise static web page you can include data from your BinaryOps app, even if it's secured and requires a login. Using the same quick-and-dirty REST API created in the PHP demo, we can demonstrate how easy it is to do with jQuery.

Add jQuery to your page

I'm going to assume you're adding API data to an otherwise static page. If you have other things going on, you should be familiar enough with JavaScript to know if you need to include jQuery or not.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Add UI elements that we can wire to a Login function

To keep things as simple as possible, I'm not adding any UI goodness to style the page, only some basic layout elements.

<div id="login-wrap" style="display:none;">
    <fieldset>
       <legend>Login</legend>
        <form id="login-form">
            <label for="username">Username</label>
                <input type="text" id="username" placeholder="Enter User Name" />
            <label for="password">Password</label>
            <input type="password" id="password" placeholder="Enter Password" />
                <button id="login-btn">Login</button>
        </form>
    </fieldset>
</div>

Next we need to include a 'script' tag and start adding our login function. I'm going to add a urlBase variable so we don't need to repeat it throughout the script.

Because our API requires authentication, we need to store the authorization token somewhere. You could put it into a session cookie, or add it to browser local storage. I'm just adding it as a property of the global 'window' variable because I'm lazy. This means, of course, that reloading the page means you're no longer authenticated.

On the .ajax() function call, we need to pass in the base64 encoded username & password in the authorization header. I understand that IE9 and friends don't support bota() & atob() methods, so you will have to find an alternative if you need IE support.

There's no data to post & the default Content-Type is sufficient for the call to /login. If the login attempt is successful, we'll store the resulting token for additional API requests.

<script type="text/javascript">

    var urlBase = "https://api.binaryops.io/v1/feedback";
    window.authorization = undefined;

    // **************************************
    // LOGIN
    // **************************************
    $('#login-btn').on('click', function (e) {
        var pwd = $("#password").val();
        var unm = $("#username").val();

        //build the basic auth value for the login
        var basic_auth = "Basic "
                         + window.btoa(unm + ':' + pwd);
        var login_url = urlBase + "/login";

        //make the login call
        $.ajax({
            url: login_url,
            type: 'POST',
            headers: { 'authorization': basic_auth },
            success: function (data) {
                window.authorization = "Bearer "
                                       + data.token;
                $("#login-user").text(unm);
                $("#password").val('');
                $("#username").val('');
                $("#login-wrap").hide();
                $("#list-wrap").show();
                $('#refresh-btn').click();
            },
            error: function (xhr, status, err) {
                alert("Login failed");
            }
        });
        return false;
    });

About Me

Now that we're authenticated we can do all kinds of cool things with our API. The first of which is to inspect our user object to see what we can do.

// About the account we've just logged in with
var me_url = urlBase + "/me";

Sending a GET request to the above URL will give you information about your user account. Here's the reply for this example user:

{
  "email": "sample@user.com",
  "display_name": "sample@user.com",
  "username": "sample@user.com",
  "privs": {
    "comments": "CRUD"
  }
}

You can see it has full CRUD (Create, Read, Update, Delete) access to the /comments collection when it's logged in. It's a handy method when displaying current user details client-side.

Get some data

Let's create a URL to get the last 10 comments. We can use the "_sort" operator to sort the feedback and by prefixing the column name with "-", we can sort them with the most recent first.

// query string to fetch the last 10 Comments
var data_url = urlBase + "/comments?_limit=10&_sort=-created_date_audit";

Adding the following ajax call to our page to get our Comments, we can build out the HTML to display each one to the user. Setting the jQuery .html() value is a valid way to insert dynamic content into your pages, but there are better ways to do it that are beyond the scope of this post. For our purposes here, it does the job. Note: Each time we replace the table rows, we'll attach a Delete handler using the 'delete-btn' class on an element included in each row.

 //make the get-data call
 $.ajax({
     url: data_url,
     type: 'GET',
     headers: {  'Content-Type': 'application/json', 
             'authorization': window.authorization },
     data : "",
     success: function (data) {
         list = "";
         if ($.isArray(data) && data.length > 0) {
             for (var i=0; i < data.length; i++) {
                 list += "<tr><td>"
                         + escapeHtml(data[i].name)
                         + "</td><td>"
                         + escapeHtml(data[i].description)
                         + "</td>";

                 list += "<td><a href='#'"
                       + " class='delete-btn' data-id=\""
                       + escapeHtml(data[i]._id)
                       + "\">Delete</a></td></tr>\n";
             }
         } else {
             list += "<tr><td colspan='3'>"
                  + "No data for you...</td></tr>\n";
             list += "<tr><td colspan='3'>"
                  + escapeHtml(data)+"</td></tr>\n";
         }
         $("#list-content").html(list);

         // attach the delete click handler
         $(".delete-btn").click (function (e) {
             var id = $(this).data('id');
             deleteById(id);
         });
     },
     error: function (xhr, status, err) {
         alert("Data request failed");
     }
 });

We've included some simple error handling there and an option for the case where there is no data to be displayed. I intentionally ignored the escapeHtml function 'cause it's not really part of the functionality being demonstrated. It's more a necessity of how we're using the data than anything.

 var escapeHtml = function(myString) {
          var entityMap = {
             "&": "&amp;",
             "<": "&lt;",
             ">": "&gt;",
             '"': '&quot;',
             "'": '&#39;',
             "/": '&#x2F;'
         };
         return String(myString).replace(/[&<>"'\/]/g, function (str) {
             return entityMap[str];
         });
     };

Try the Demo

You can see this jQuery demo in action and try it out for youself.

See the demo

Using jQuery to login and fetch data with a BinaryOps.io REST API is probably the simplest way to kick the tires of any CORS enabled API and the number of ways we could use it is only limited by the imagination.

If you have questions or comments, use the ‘?’ widget in the corner and let us know how you've used your BinaryOps.io API!

Tags :  jquery  api