Tuesday 10 February 2015

Using Font Awesome icons and jQuery to show form loading in Twitter Bootstrap page

Font Awesome is a really useful tool for adding icons to your website. It also comes with animated icons which can be used to show when your form is waiting for a response. In the example below, I have created a basic Twitter Bootstrap page. The page has a form. When the form is submitted, there is a delay in its response. During the delay, I use jQuery to show a Font Awesome animated icon.
First the Twitter Bootstrap page with the differences in red:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Font Awesome Animated Icons</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">   
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
  <i class="fa fa-circle-o-notch fa-spin"></i>  
  <form action="response.php" method="POST">
    <input type="text" name="yourname" id="yourname" placeholder="Enter your name" />
    <button type="submit">Submit</button>
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script>
  (function()
  {
    var thisForm = $('form');
    var i = $('i');
    i.hide();
    thisForm.submit(function()
    {
      i.show();
      thisForm.hide();
      $.post(thisForm.attr('action'),thisForm.serialize(), 
      function(data)
      {
        thisForm.empty().html(data);
        i.hide();
        thisForm.show();
      });  
      return false;
    });
  })();
  </script>
  </body>
</html>
Now my response.php
<?php
sleep(2);
echo 'Hello '.$_POST['yourname'];
?>

Thursday 5 February 2015

JS and CSS fall back using PHP

There are several solutions to JS and CSS out there on the web. I've tried quite a few, but I find that if I take my network connection out, they don't work. They don't fall back. Recently, maxcdn.bootstrapcdn.com went down causing websites, including my own, to suffer from a lack of bootstrap. Even though I'd put in some fall back code.
This prompted me to write the following code. Now I know I'll be criticised for using PHP as the solution, but if you've suffered as I have, you may consider this worth a try. Below is the PHP class followed by the HTML page which makes use of the class with the calls highlighted in red. In this case I'm calling Twitter Bootstrap.
callfallback.class.php
<?php
class callfallback
{
function __construct()
{

}

function getCSS($remote, $local)
{
if($this->testExists($remote) == TRUE)
{
echo '<link rel="stylesheet" href="'.$remote.'" />'.PHP_EOL;
}
else
{
echo '<link rel="stylesheet" href="'.$local.'" />'.PHP_EOL;
}
}

function getJS($remote, $local)
{
if($this->testExists($remote) == TRUE)
{
echo '<script src="'.$remote.'"></script>'.PHP_EOL;
}
else
{
echo '<script src="'.$local.'"></script>'.PHP_EOL;
}
}

function testExists($url)
{
$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 OK')
{  
 return TRUE;
}
else
{
 return FALSE;
}
}

function __destruct()
{

}
}
?>
index.html
<!DOCTYPE html>
<?php
require_once 'callfallback.class.php';
$cfb = new callfallback;
?>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap Fallback Template</title>
  <?php
  $cfb->getCSS('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css','css/bootstrap.min.css');
  ?>
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
  </head>
  <body>
 
  <?php
  $cfb->getJS('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js','js/jquery-1.11.2.min.js');
  $cfb->getJS('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js','js/bootstrap.min.js');
  ?>
</body>
</html>

Monday 8 December 2014

Dynamically activate navigation items in Bootstrap using my jQuery plugin

My challenge was to write a piece of jQuery which:

  • Takes note of the page path.
  • Compares it with the Bootstrap navigation.
  • Makes the navigation element 'active' to remind the users where they are in relation to the site.

First the HTML. Notice, that I have not set any navigation item as active. The plugin will do this. The plugin call is in red.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Activate Navigation Entry</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar navbar-default" role="navigation">
      <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li><a href="index.php">Home</a></li>
            <li><a href="about.php">About</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">
                <li><a href="action.php">Action</a></li>
                <li><a href="anotheraction.php">Another action</a></li>              
              </ul>
            </li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container -->
    </nav>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <h1>Home</h1>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    <script src="activatenav.plugin.js"></script>
    <script>
    (function()
    {
      $(document).activatenav(
      {
        toplevel:'ul.nav.navbar-nav > li > a',
        dropdown:'ul.nav.navbar-nav > li.dropdown > ul.dropdown-menu > li > a'
      });
    })();
    </script>
  </body>
</html>
Next the jQuery plugin named 'activatenav.plugin.js'.
First calculate the end of the path. If there is no name, it must be the home page, so set that as active.
I also check if the current page is from the drop down menu. If so, set both the drop down heading and the corresponding navigation item as 'active'.
(function($)
{
    $.fn.extend(
    {
        activatenav:function(options)
        {
        var pname = window.location.pathname;
        var pArr = pname.split('/');        
            var defaults =
            {
                toplevel:'',
        dropdown:''
            };
            options = $.extend(defaults, options);
if(options.toplevel)
{
handled = $(this).handleTopLevel(options.toplevel, pArr[pArr.length-1]);
if(handled == false)
{
$(this).handleDropdown(options.dropdown, pArr[pArr.length-1]);
}
}
        }
    });

    $.fn.handleTopLevel = function(str, pth)
    {
    var hd = false;  
    if(!pth)
    {
    $(str).first().parent().addClass('active');
    }
    else
    {
    $(str).each(function()
    {
    if($(this).attr('href') == pth)
    {
    $(this).parent().addClass('active');
    hd = true;
    }    
    });
    }
    return hd;  
    };

    $.fn.handleDropdown = function(str, pth)
    {
        $(str).each(function()
    {
    if($(this).attr('href') == pth)
    {
    $(this).parent().addClass('active');
    $(this).closest('li.dropdown').addClass('active');
    }    
    });
    };
})(jQuery);

Monday 10 November 2014

Extend your footer to the browser window using jQuery

Some pages only have a small amount of content and aesthetic reasons you'l like your page footer to extend all the way to the edge of the browser window. There are ways to do this using CSS, but this method also requires to to code your pages differently too. I like to keep the code of my pages straight forward. HTML should not be altered for styling purposes.
So I wrote a jQuery plugin to do this. See below.
(function($)
{
    $.fn.extend(
    {
        footersizeset: function(options)
        {
            var defaults =
            {
                footertag:'footer',
                ofh:100
            };
            options = $.extend(defaults, options);
    var windowheight = $(this).height();
var footer = $(options.footertag);
var footerposition = footer.position();
var footerheight = options.ofh;
var footerbottom = footerheight + footerposition.top;

if(windowheight > footerbottom)
{
difference = windowheight - footerbottom;
footer.height(footerheight + difference);
}
        }
    });
})(jQuery);

Here's how to call the plugin. First you find what the height of the footer would be before the footer is reset. This is done outside all other jQuery calls so that this value doesn't keep getting reset as the browser window size changes.
Then, I make 2 calls to the plugin, once for the page load and subsequently for browser window changes.

var originalfooterheight = $('footer').height();
(function()
{
$(window).footersizeset(
{
footertag:'footer',
ofh:originalfooterheight
});
$(window).resize(function()
{
$(this).footersizeset(
{
footertag:'footer',
ofh:originalfooterheight
});
});
})();

Hope that makes sense.

Tuesday 4 November 2014

Twitter Bootstrap Simple One Page Template

The code below will give you a good starting position if you need to create a one page website using Twitter Bootstrap. It uses basic jQuery animation techniques so there's no need to load another library. The most important elements which get it to work are highlighted in red.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap One Pager</title>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
    <style>
    .row
    {
      padding-top:4em;
    }
    figure > img
    {
      width:100%;
    }    
    </style>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">My Website</a>
        </div><!-- .navbar-header -->
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li><a href="#home">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div><!-- .nav-collapse -->
      </div><!-- .container -->
    </nav>

    <div class="container">
      <div class="row" name="home" id="home">
        <article class="col-md-6">
          <h2>Home</h2>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>  
          <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Estne, quaeso, inquam, sitienti in bibendo voluptas? Servari enim iustitia nisi a forti viro, nisi a sapiente non potest. Cum salvum esse flentes sui respondissent, rogavit essentne fusi hostes. Audax negotium, dicerem impudens, nisi hoc institutum postea translatum ad philosophos nostros esset. Obsecro, inquit, Torquate, haec dicit Epicurus? Quamquam haec quidem praeposita recte et reiecta dicere licebit. Non dolere, inquam, istud quam vim habeat postea videro; Nobis Heracleotes ille Dionysius flagitiose descivisse videtur a Stoicis propter oculorum dolorem. Duo Reges: constructio interrete. Dici enim nihil potest verius.</p>
          <p>Quid ergo attinet dicere: Nihil haberem, quod reprehenderem, si finitas cupiditates haberent? Deprehensus omnem poenam contemnet. Ego vero volo in virtute vim esse quam maximam; Omnis enim est natura diligens sui. Semper enim ex eo, quod maximas partes continet latissimeque funditur, tota res appellatur. Graecum enim hunc versum nostis omnes-: Suavis laborum est praeteritorum memoria. Hoc loco tenere se Triarius non potuit.</p>
          <p>Tu quidem reddes; Dicet pro me ipsa virtus nec dubitabit isti vestro beato M.</p>
          <p>Quod iam a me expectare noli. Hoc est dicere: Non reprehenderem asotos, si non essent asoti. Saepe ab Aristotele, a Theophrasto mirabiliter est laudata per se ipsa rerum scientia; Alterum significari idem, ut si diceretur, officia media omnia aut pleraque servantem vivere. Nec vero sum nescius esse utilitatem in historia, non modo voluptatem. Cur iustitia laudatur?</p>
          <p>Atque hoc loco similitudines eas, quibus illi uti solent, dissimillimas proferebas. Quamquam ab iis philosophiam et omnes ingenuas disciplinas habemus; Neque enim disputari sine reprehensione nec cum iracundia aut pertinacia recte disputari potest. Ita enim vivunt quidam, ut eorum vita refellatur oratio. Unum est sine dolore esse, alterum cum voluptate. Qua tu etiam inprudens utebare non numquam. An est aliquid per se ipsum flagitiosum, etiamsi nulla comitetur infamia? Intrandum est igitur in rerum naturam et penitus quid ea postulet pervidendum; Quod ea non occurrentia fingunt, vincunt Aristonem;</p>
        </article>
        <figure class="col-md-6">  
          <img src="http://lorempixel.com/400/200/sports" alt="sports" class="img-responsive" />
          <figcaption>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</figcaption>
        </figure>
      </div><!-- .row -->
      <div class="row" name="about" id="about">
        <article class="col-md-6">
          <h2>About</h2>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>  
          <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Estne, quaeso, inquam, sitienti in bibendo voluptas? Servari enim iustitia nisi a forti viro, nisi a sapiente non potest. Cum salvum esse flentes sui respondissent, rogavit essentne fusi hostes. Audax negotium, dicerem impudens, nisi hoc institutum postea translatum ad philosophos nostros esset. Obsecro, inquit, Torquate, haec dicit Epicurus? Quamquam haec quidem praeposita recte et reiecta dicere licebit. Non dolere, inquam, istud quam vim habeat postea videro; Nobis Heracleotes ille Dionysius flagitiose descivisse videtur a Stoicis propter oculorum dolorem. Duo Reges: constructio interrete. Dici enim nihil potest verius.</p>
          <p>Quid ergo attinet dicere: Nihil haberem, quod reprehenderem, si finitas cupiditates haberent? Deprehensus omnem poenam contemnet. Ego vero volo in virtute vim esse quam maximam; Omnis enim est natura diligens sui. Semper enim ex eo, quod maximas partes continet latissimeque funditur, tota res appellatur. Graecum enim hunc versum nostis omnes-: Suavis laborum est praeteritorum memoria. Hoc loco tenere se Triarius non potuit.</p>
          <p>Tu quidem reddes; Dicet pro me ipsa virtus nec dubitabit isti vestro beato M.</p>
          <p>Quod iam a me expectare noli. Hoc est dicere: Non reprehenderem asotos, si non essent asoti. Saepe ab Aristotele, a Theophrasto mirabiliter est laudata per se ipsa rerum scientia; Alterum significari idem, ut si diceretur, officia media omnia aut pleraque servantem vivere. Nec vero sum nescius esse utilitatem in historia, non modo voluptatem. Cur iustitia laudatur?</p>
          <p>Atque hoc loco similitudines eas, quibus illi uti solent, dissimillimas proferebas. Quamquam ab iis philosophiam et omnes ingenuas disciplinas habemus; Neque enim disputari sine reprehensione nec cum iracundia aut pertinacia recte disputari potest. Ita enim vivunt quidam, ut eorum vita refellatur oratio. Unum est sine dolore esse, alterum cum voluptate. Qua tu etiam inprudens utebare non numquam. An est aliquid per se ipsum flagitiosum, etiamsi nulla comitetur infamia? Intrandum est igitur in rerum naturam et penitus quid ea postulet pervidendum; Quod ea non occurrentia fingunt, vincunt Aristonem;</p>
        </article>
        <figure class="col-md-6">  
          <img src="http://lorempixel.com/400/200/cats" alt="sports" class="img-responsive" />
          <figcaption>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</figcaption>
        </figure>
      </div><!-- .row -->
      <div class="row" name="contact" id="contact">
        <article class="col-md-6">
          <h2>Contact</h2>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ad utilitatem tantae pecuniae? Age, inquies, ista parva sunt. Quibus ego vehementer assentior. Quae cum essent dicta, discessimus.</p>  
          <p>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</p>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Estne, quaeso, inquam, sitienti in bibendo voluptas? Servari enim iustitia nisi a forti viro, nisi a sapiente non potest. Cum salvum esse flentes sui respondissent, rogavit essentne fusi hostes. Audax negotium, dicerem impudens, nisi hoc institutum postea translatum ad philosophos nostros esset. Obsecro, inquit, Torquate, haec dicit Epicurus? Quamquam haec quidem praeposita recte et reiecta dicere licebit. Non dolere, inquam, istud quam vim habeat postea videro; Nobis Heracleotes ille Dionysius flagitiose descivisse videtur a Stoicis propter oculorum dolorem. Duo Reges: constructio interrete. Dici enim nihil potest verius.</p>
          <p>Quid ergo attinet dicere: Nihil haberem, quod reprehenderem, si finitas cupiditates haberent? Deprehensus omnem poenam contemnet. Ego vero volo in virtute vim esse quam maximam; Omnis enim est natura diligens sui. Semper enim ex eo, quod maximas partes continet latissimeque funditur, tota res appellatur. Graecum enim hunc versum nostis omnes-: Suavis laborum est praeteritorum memoria. Hoc loco tenere se Triarius non potuit.</p>
          <p>Tu quidem reddes; Dicet pro me ipsa virtus nec dubitabit isti vestro beato M.</p>
          <p>Quod iam a me expectare noli. Hoc est dicere: Non reprehenderem asotos, si non essent asoti. Saepe ab Aristotele, a Theophrasto mirabiliter est laudata per se ipsa rerum scientia; Alterum significari idem, ut si diceretur, officia media omnia aut pleraque servantem vivere. Nec vero sum nescius esse utilitatem in historia, non modo voluptatem. Cur iustitia laudatur?</p>
          <p>Atque hoc loco similitudines eas, quibus illi uti solent, dissimillimas proferebas. Quamquam ab iis philosophiam et omnes ingenuas disciplinas habemus; Neque enim disputari sine reprehensione nec cum iracundia aut pertinacia recte disputari potest. Ita enim vivunt quidam, ut eorum vita refellatur oratio. Unum est sine dolore esse, alterum cum voluptate. Qua tu etiam inprudens utebare non numquam. An est aliquid per se ipsum flagitiosum, etiamsi nulla comitetur infamia? Intrandum est igitur in rerum naturam et penitus quid ea postulet pervidendum; Quod ea non occurrentia fingunt, vincunt Aristonem;</p>
        </article>
        <figure class="col-md-6">  
          <img src="http://lorempixel.com/400/200/people" alt="people" class="img-responsive" />
          <figcaption>Invidiosum nomen est, infame, suspectum. Duo Reges: constructio interrete. Quibus ego vehementer assentior. Non igitur bene.</figcaption>
        </figure>
      </div><!-- .row -->
    </div><!-- .container -->

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script>
    (function()
    {
      $('.navbar-inverse .navbar-nav > li > a').click(function()
      {
        var target = $(this).attr('href');
        var targetLoc = $(target).offset().top;        
        $('html, body').stop().animate(
        {
          scrollTop:targetLoc,
          easing:'swing'
        }, 1000);
        return false;
      });
    })();
    </script>
  </body>
</html>

Monday 6 October 2014

Using PHP to get YouTube Channel feed into Twitter Bootstrap thumbnails

I've been working on a Twitter Bootstrap site. The client created a YouTube channel and wanted the feed coming into the site. Some of the videos added are uploaded by the users, some come from subscriptions. There is a nice class called thumbnail in Twitter Bootstrap for such things, so I thought I'd use that. I'm happiest getting external data using PHP. Here's how it's done.
Replace the word 'Google' with the name of your channel.
<?php
$url = 'https://gdata.youtube.com/feeds/api/videos?q=Google&max-re%20sults=5&v=2&alt=jsonc&orderby=published';
$json = file_get_contents($url);
$data = json_decode($json);
$items = $data->data->items;
foreach($items as $child)
{
echo '<a href="'.$child->player->default.'" class="thumbnail">';
echo '<h4>'.$child->title.'</h4>';
echo '<img src="'.$child->thumbnail->sqDefault.'" alt="'.$child->title.'" />';
echo '<footer>'.date("jS F Y",strtotime($child->updated)).'</footer>';
echo '</a>';
}
?>

Wednesday 1 October 2014

jQuery file upload in Twitter Bootstrap modal

For a recent project, I have needed to add a file upload form to a modal. This has required me to perform the upload through jQuery in order to avoid the page reloading when the form is submitted.
To accomplish this I have used the jQuery form plugin at http://malsup.com/jquery/form/.
Here's the code with the important bits highlighted in red.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style>
    body
    {
    padding-top:2em;
    }
    </style>
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
  <div class="container">
  <div class="col-md-6">
  <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
 
  </div>
  <div id="myResult" class="col-md-6 alert alert-success" role="alert">
 
  </div><!-- myResult -->
  </div><!-- .container -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
   <div class="modal-content">
     <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
       <h4 class="modal-title">Modal title</h4>
     </div>
     <div class="modal-body">
       <form action="uploadfile.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="file">File input</label>
<input type="file" name="file">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
     </div>
   </div><!-- /.modal-content -->
 </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.50/jquery.form.min.js"></script>
    <script>
(function()
{
$('#myResult').hide();
$('form').submit(function()
{
$(this).ajaxSubmit(
{
url:$(this).attr('action'),
method:$(this).attr('method'),
target: '#myResult'
});
$('#myModal').modal('hide');
$('#myResult').show();
return false;
});
})();
</script>
  </body>
</html>