Tag Archives: jquery

Trigger Basic Auth Dialog with jQuery / AJAX

05 May 2017

We’re all familiar with basic authentication (or should be) – my experience with it has been via cPanel or doing it by hand on *nix servers. Once setup it just works. The other day I was integrating an app into a service where the dev environment had basic authentication on it. My AJAX calls were blocked (naturally) but did not trigger a username/password dialog to appear. I had assumed that the browser would just “do its thing”.

What is happening behind the scenes is that my AJAX call causes the server to return a 401 HTML error page. This is an unexpected response that jQuery can’t handle and that will cause the following error in the console:

$ Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()

jQuery will also return a status code “0” which, by the way, is a generic error from jQuery. As the response from the server was an HTML document (401 error page) jQuery couldn’t parse it (it was expecting the response to be JSON) thus the above error. Lacking any proper status code to use jQuery then just uses “0”.

Lastly if I inspect the response header I can see that WWW-Authenticate: Basic appears. That’s a clue as to what we should do to get things working which is to add a Authorization:Basic header to our AJAX request to begin with.

We can add the necessary header by specifying the beforeSend callback when we configure the AJAX request. Inside of the callback we can create the Authorization header that will be added to our request. See the following example:

      method: 'POST',
      contentType: 'application/json',
      url: 'service URL here'
      data:'data here',
      beforeSend: function (xhr) {
        xhr.setRequestHeader ('Authorization', 'Basic xxxx');
    .done(function( data, textStatus, jqXHR ) {
      // do something here...
    .fail(function( jqXHR, textStatus, errMsg ){
      // do something here...

Here you can see that we are setting the “Authorization” header via xhr.setRequestHeader. The spec says that Basic should be followed by a base-64 representation of the user name and password to authenticate with but in this case we are using an arbitrary string. Since its obviously wrong the server will respond by asking for the correct credentials; the authentication dialog will appear.

As you can see there is some interaction going back and forth between the client and the server. If you’re attentive to the network tab in the Chrome console you can see the handshaking as it happens.

Templating with jQuery

11 Jan 2016

There are a few templating libraries available which you could use to create templates for your apps. While its easy enough to learn how to use them you could also just as easily create your own external template files for your jQuery-based projects using the jQuery skills you already have. Discussed here is a simple way of including HTML templates into your jQuery work.


Templates provide a way of separating layout from code. As such, they have various methods of indicating where data is to be inserted into the template. In our case we’ll use class and ID selectors in the HTML itself and thus be able to use jQuery’s existing methods to manipulate the template.

The data to be inserted into our templates can take the form of strings, numbers, objects or some sort of array. Arrays mean that you likely have a repeating region. The available templating libraries (Underscore, Handlebars, etc) or frameworks that have built-in templating (Sencha Touch, Angular, etc) provide methods that abstract the process of looping through arrays to display lists or tables. These libraries and frameworks also provide helper functions for things such as string formatting and conditional logic to add intelligence to the template.

While built-in helper methods are a handy feature this article will assume that you’ll build your own by leveraging jQuery’s features. For our purposes I’ll assume that you only need the most basic type of template and that will be one that has identified in some way what portions of the template itself will be used/substituted or otherwise populated with your desired data.

Setup a Template

Our template will be an HTML file – a properly formed file complete with all of the required HTML elements, ie., html, head, title & body tags. Basically, you will layout your page so that it represents one specific type of view within your application. Save your templates in a folder called “templates” in some logical area of your app/site.

While you are laying out your page you are naturally creating CSS class and ID selectors for you page elements. While you are doing this you are also likely using greeked-in text or “for-position-only” images so that you can realize your layout. Also, you should build the template with an eye towards the areas that need to be populated with text, images or whatever the case might be. With this last point in mind you should pay attention to the class/ID selectors that you give to your DOM elements as that will be what we use to manipulate the template.

Since we mentioned CSS, your style sheet should be an external style sheet that your app/site loads up. This way when the template is used all of the necessary styling will already be present. If you are the sort that doesn’t want stylesheets loaded that aren’t yet needed then figure out a way to inject them into your page – we are using jQuery so this should be an easy task – understand that today’s discussion is only about templates not dependency management 🙂 (though honestly, the link to the external CSS could be added to the template HTML, then you create a query selector to grab it when the template is loaded and then….. but I digress…)

Sample Template

Here’s a sample template from a project that I recently worked on.



Pretty basic. Note that the actual template is the one with the #interactive ID. The rest of the page is just filler for the layout guys on my team.

Within the #interactive DIV I used ID selectors for the elements that would need to be populated with text. Also, while I didn’t keep any dummy text in the template you could easily insert greek text so that you can see what the layout looks like without having to first run it through your app. That’s the nice part about using this kind of templating workflow, that your teammates can focus on layout while you focus on developing the application without worrying about stepping on each other’s work.

Worth noting here is that like in any project you have a header and a footer. The same with this template. Recall that we mentioned that it was nice to be able to look at a template outside of your application to see it in its entirety without impacting development. That would assume that the header and footer be present even though it isn’t needed. You could of course elect not to include these two page features for many reasons, not the least of which would be to make a smaller template file that loads that much faster. This example for better or worse includes the header (denoted by the topBlueBar and logo ID’s) and the footer (denoted by the controlsWrapper).

It is of course true that you can add some automation via Gulp or similar to strip the header and footer from the templates in order to give the layout guys the benefit of viewing their work in-context and the more picky developers the desire to strip out what would be considered wasteful…. however you want to deal with it, its entirely up to you. Again, both header and footer are presented here and will be dealt with in the next section.

Before we proceed look at that wrapping div element on line 5 – this is **necessary** as without it the template will not work in the way that we might expect. We’ll explain why in the next section.

Load the Template

This is the most difficult part (not that its at all difficult) – loading a template. You simply need to make an AJAX call to load up the file. Here’s an example:

var _templates = {}; // save your templates so that you can re-use them
$.get('templates/content_tpl.html', function(template){
    // in this example, we're calling the template "sample_template" and assigning the template as a DOM object as its value
    _templates.sample_template = $('
').append($($.parseHTML(template)).find('#interactive').html()); });

Hopefully the above is clear but lets quickly break things down.

First, $.get() loads data from the server using a GET request. We are passing the local path to the desired template HTML file.

Next, the file that is returned to us is text which isn’t as useful to us as it could be so we convert it into an array of DOM nodes. This is crucial so that we can use jQuery’s DOM-manipulation methods on the template instead of having to resort to string or regular expression methods.

Now that the page has been converted to jQuery DOM nodes we look for the template area itself which is denoted by the DIV with the #interactive ID.

Finally we assign the resulting DOM nodes to a property of the _templates element so that we can use it in the future.

Interestingly we now can get back to that wrapping DIV mentioned in the previous “Sample Template” section. Without it in place our #interactive query selector won’t work because what will happen is that jQuery will search the first DIV in the page, which of course doesn’t contain the div#interactive element. By wrapping everything in a DIV jQuery is then able to traverse all the nodes and find the desired element.

In case you didn’t realize what just happened – we extracted only the template HTML from the template. Everything else is being discarded. So the header and footer HTML that was part of the template HTML file itself is not what we will be working with moving forward.

Using the Template

Recall that we converted the string result of the AJAX get to DOM nodes, that we pulled out only the nodes that we needed, and that we saved the result to _templates.sample_template.

Using the template is simple: do what you always do in a page where you want to change the values or inner html of page elements:

// get a deep copy of the template
var tpl =  JSON.parse(JSON.stringify(_templates.sample_template));

// populate the template
tpl.find('#title').html('This is my first template');
tpl.find('#subTitle').html('This is a subtitle');

// now insert the template html into your app
// where our app already has a #templateArea DIV within it so
// this is a simple insert 

Notice that we can easily manipulate our template using the usual jQuery DOM manipulation methods. Also, it would be a simple matter to pull out a chunk of DOM nodes to iterate through a list and then reinsert them back into the tpl.

From here you can start to flesh out your home-grown templating system. Adding methods for formatting dates, dollar amounts, or handling repeating areas like lists or tabular data.

jqPlot Memory Leak

20 Nov 2013

Today I was brought into a conversation with our iOS developer about a portion of a client’s app that utilizes a charting component done in jQuery that is displayed via a web view. TestFlight showed the app crashing during prolonged use of the charting application. The first thing I thought was that memory wasn’t being released so I told the team I would look into it.

I ran the charting app in Chrome and watched the memory usage via the developer tool’s timeline. Sure enough, the familiar memory leak pattern became visible:


Using the tools Chrome provides to isolate a portion of the timeline and investigate what is happening revealed a theme of a “chart()” function being called. I tracked down where that was happening – and in the process discovered that jqPlot was in use (I had no previous experience with the app). I typed in a return statement at a stratgic spot to prevent charting from happening and then proceeded to once again torture the app and review the timeline. As you can see, the memory leak was gone:


No leak – the charting functions are the culprit – a quick search online revealed other people having the issue and one individual mentioning that jqChart has a “destroy” method that releases memory. Perfect, lets review our code again… and yes, all that is happening is that the previous developer is emptying the div wrapper of the chart data before filling it with a new one. That’s not releasing memory.

Here is the code before my edit:

var plot1 = $.jqplot ('the_chart', [fcccPoints, brandXPoints, crossoverPoint],

The div wrapper is unceremoniously emptied and the call to jqplot is assigned to a local variable. I needed to keep the reference to the chart so that I can destroy it properly so I moved the variable declaration outside of the function’s scope. I then changed the code to the following:

if (plot1){
    console.log('plot destroyed');
plot1 = $.jqplot ('the_chart', [fcccPoints, brandXPoints, crossoverPoint],

With those two tiny edits I again torture-tested the app and observed the timeline. As you can see jqPlot’s destroy method was doing its job and memory was now being reclaimed.


Mixing jQuery and reCaptcha in Forms

06 Oct 2013

The business of collecting user data includes the ubiquitous form. The thing with forms is that they are the first to see abuse on the Internet and if left unprotected your inbox or database will soon be overrun with spam. One of many methods of protecting forms is the CAPTCHA. CAPTCHAs require that a user interpret a randomly-generated image by typing its value into a text field. Since automated programs (bots) can’t read the image they are stopped cold. Humans and their famously short attention spans happen to have enough bandwidth to tolerate a CAPTCHA or two. The Spammer variants, on the other hand, seem to lack the patience needed and will quickly move on to easier pickings of which there are untold thousands. So then, while a CAPTCHA is a minor inconvenience to your end-users it’s presence more than makes up for itself by its ability to completely stave off an avalanche of useless form posts.

Google provides a CAPTCHA service called reCAPTCHA which is the subject of this article.

The workflow I’ll be implementing is the following:

  1. User “submits” form
  2. The form is validated
  3. If form validation succeeds I then make an AJAX call to the reCaptcha service via a proxy to see if the user entered the correct reCaptcha value
  4. If an incorrect value was entered I’ll display an in-line message to the user
  5. If the correct value was entered I will submit the form

You can see this process in action below:

Register for a set of reCAPTCHA keys

You must first sign up to use reCAPTCHA by visiting http://www.google.com/recaptcha. After you register click the “Add Site” link and add your site. After you add a site you will get 2 keys – keep these handy, we’ll need them later.

Download the reCAPTCHA PHP Library

You will also need to download the reCAPTCHA PHP Library (I’m assuming that your site is on a PHP-compatible server).

Setting up a proxy

Since we plan on making AJAX calls to the reCAPTCHA service we know we will need a proxy as we would otherwise run afoul of the browser’s cross-domain policy. The way we will circumvent this is by creating a proxy. This proxy will handle communication between our web page and reCAPTCHA by forwarding our submitted form data to the reCAPTCHA service which in return responds to the proxy and then the proxy hands the response back to our web page.

The reCAPTCHA PHP library contains everything we need to setup our proxy. The library contains 5 files – we will be using 2 of them:

  • recaptchalib.php
  • example-captcha.php

The second file – example-captcha.php – will need to be modified for our purposes. Here is the original file (this is version 1.11) before any changes:

    <form action="" method="post">


// Get a key from https://www.google.com/recaptcha/admin/create
$publickey = "";
$privatekey = "";

# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;

# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
        $resp = recaptcha_check_answer ($privatekey,

        if ($resp->is_valid) {
            echo "You got it!";
        } else {
             # set the error code so that we can display it
             $error = $resp->error;
echo recaptcha_get_html($publickey, $error);
    <input type="submit" value="submit" />

To get to where we need to be we need to remove all html and make a couple of tiny changes to the PHP. I won’t walk through them in detail opting instead to just show you the finished edited file (the savvy among you will no doubt notice the differences) and to mention that the public and private reCAPTCHA keys are in use here:



// Get keys from https://www.google.com/recaptcha/admin/create
$publickey = "YOUR_PUBLIC_KEY_HERE";
$privatekey = "YOUR_PRIVATE_KEY_HERE";

# the response from reCAPTCHA
$resp = null;

# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
    $resp = recaptcha_check_answer ($privatekey,

    if ($resp->is_valid) {
        echo "success";
    } else {
        echo "failure";

The line that echoes “success” is what we will be listening for in our AJAX call to determine if the reCAPTCHA verification was successful.

At this point your proxy is done. Go ahead and place your modified example-captcha.php and the unchanged recaptchalib.php on your server in the same folder as your form.

Add the jQuery and reCAPTCHA JS Libraries

You need to add these two lines within the head of your document (use whatever version of jQuery your project requires):

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js">

Setting up your form

The form code below is pretty basic – things to pay attention to:

  • This is a template for the reCAPTCHA functionality only – you still need to configure your form to work with your form remailer (i.e., gdform.php on GoDaddy, formmail.php, cgiemail or whatever the case might be)
  • Note the onsubmit=”return doForm()” in the FORM tag – this is the hook to our JavaScript that communicates to the reCAPTCHA server
  • There are 2 divs present:

    • <div id=”recap”></div> this is the wrapper for the reCaptcha itself
    • <div id=”err”>…</div> This is the in-line error message that we will display if the reCAPTCHA verification fails.
  • Note the style tag – we have a css class called “hidden” that is assigned to the reCAPTCHA error div. If there is an error we use jQuery to remove the class and show the error message to the user
<style type="text/css">
    /* place the style in your stylesheet or move this to the head of your document */

<!-- note the onsubmit="return doForm()" - your FORM tag must contain this -->
<form action="test.php" method="post" name="form1" id="form1" onsubmit="return doForm()">

    <!-- your form fields would go in here -->
    Name: <input class="textInput" name="Name" type="text" id="name" size="55" maxlength="55" />

    <!-- The reCAPTCHA wrapper is here - this is required!! -->
    <div id="recap"></div>

    <!-- the reCAPTCHA error div is next, edit/style as you see fit -->
    <div id="err" class="hidden" style="background-color:#FFFF00;color:#FF0000;margin:12px 0px 12px 0px;">The Captcha was not entered correctly. Please try again.</div>

    <!-- the submit button -->
    <input type="submit" name="button" id="button" value="Submit" />

Inserting the reCAPTCHA, validating Form and reCAPTCHA input

Next we need to insert the reCAPTCHA elements into the document. In the code that follows you can see that I’m inserting the reCAPTCHA on jQuery’s document.ready event.

When the form is submitted I first validate the form input which you can see in the doForm() function. If validation passes I then attempt to validate the reCAPTCHA via the recapVerify function.

Its all put together in the code snippet below (** add your public key where indicated in line 41 **):

<script type="text/javascript">

    function doForm(){
	// your form validation would go here, for example:
	var isValid = $('#name').val().length != 0 ? true : false;

	    alert('Name is required');

	} else { //FORM VALIDATION SUCCEEDED, validate the reCAPTCHA
	    recapVerify(); // verify reCAPTCHA
	return false;

    function recapVerify(){
	    url: 'captcha_proxy.php',
	    data: {
	}).done(function(data, textStatus, jqXHR){
	    if (data == 'success'){
	    } else {
            console.log('proxy or service failure');

    function reCapInsert(){
        Recaptcha.create('YOUR_PUBLIC_KEY_HERE',  // public key
                theme: 'clean',
                callback: Recaptcha.focus_response_field

    $( document ).ready(function(){

And that should do it. Download all files here.

Preventing jQuery Mobile Page Flicker

11 Jun 2013

One irritating artifact of using jQuery Mobile is the page flickering that happens when changing pages – most noticeable on Android but sometimes on iOS as well. Here’s how to get rid of it…

First, make sure you have the proper viewport meta in your document:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

This prevents the user from scaling the view as if it were a normal web page – every web app must have this in it.

Next, turn backfaces off via css like so:

.ui-page {
  -webkit-backface-visibility: hidden;

This last one assumes that you are not using native webview scrolling to scroll your content- I don’t know why you would want to – performance of native scrolling is spotty at best. So, assuming that you are not using native scrolling but are using iScroll instead then add this last item to your css:


You’re done – no more flickering.

If you aren’t using iScroll but instead are relying on native webview scrolling then you will need to enable/disable the native scrolling programmatically during page transitions/loads. You can bind to the pagebeforechange event to do the toggling for your entire project. This event fires twice, once before and once after the page change, so you can do something similar to the following:

$('.selector').on('pagebeforechange', function(e){
  var isScrollable = !$('body').hasClass('preventNativeScroll');
  if (isScrollable){
  } else {

I’ve not tested the above – its only meant for illustration.


All content © 2012-2017.