Tuesday 30 September 2014

Forms within modal-body in Twitter Bootstrap.

I've been working on a Twitter Bootstrap site recently. It contains modal which require a little interaction within the modal box itself. So here is an example of how to achieve this, this time using forms. First, I load the form into the modal, then I handle the form still within the modal. Most of the code is taken directly from the Twitter Bootstrap website. The only real difference is that I've loaded jQuery and the bootstrap.min.js before the body. I've highlighted the important parts 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>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- 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>  
    <!-- Button trigger modal -->
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">    Launch demo modal</button>
    <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 class="form-inline" role="form" method="POST" action="http.php">
  <div class="form-group">
    <label class="sr-only" for="exampleInputEmail2">Email address</label>
    <input type="email" class="form-control" name="exampleInputEmail2" placeholder="Enter email">
  </div>  
  <button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
(function()
{
  $('form').submit(function()
  {
    $.post($(this).attr('action'),$(this).serialize(), function(data)
    {
      $('#myModal .modal-body').append(data);
    });
    return false;
  });
})();
</script>
</body>
</html>

Get links to target modal-body in Twitter Bootstrap

I've been working on a Twitter Bootstrap site recently. It contains modal which require a little interaction within the modal box itself. So here is an example of how to achieve this, first using links (hyperlinks). Most of the code is taken directly from the Twitter Bootstrap website. The only real difference is that I've loaded jQuery and the bootstrap.min.js before the body. I've highlighted the important parts 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>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- 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>  
    <!-- Button trigger modal -->
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">    Launch demo modal</button>
    <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">
        <a href="hello.php" data-target="#myModal">Click me</a>
       </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
(function()
{
  $('a[data-target=#myModal]').click(function()
  {
    var target = $(this).attr('href');
    $('#myModal .modal-body').load(target);
    return false;
  });  
})();
</script>  </body>
</html>

Tuesday 15 July 2014

Post all form fields to PHP using jQuery

The example below simplifies the process of simply passing all HTML form data to a PHP script (or any other HTTP handler), obviously without a refresh. Below that are a couple of suggestions on how the jQuery and PHP could be improved beyond the simplified versions.
First the HTML and jQuery (in red).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Form test</title>
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
</head>
<body>
<form action="response.php" method="POST">
<input type="text" name="firstname" /><br />
<input type="text" name="lastname" /><br />
<button type="submit">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function()
{
$('form').submit(function()
{
$.post($(this).attr('action'),$(this).serialize(), function(data)
{
alert(data)
});
return false;
});
})();
</script>
</body>
</html>
Now the PHP script.
<?php
echo 'Received';
?>
We could improve the jQuery by clearing the form content thus.
$('form').submit(function()
{
thisform = $(this);
$.post($(this).attr('action'),$(this).serialize(), function(data)
{
thisform.trigger('reset'),
alert(data)
});
return false;
});
We could also use the PHP to create a MySQL call using the form array, thus.
<?php
$valueString = '';
$sqlString = '"INSERT INTO `tablename` (';
foreach($_POST as $key => $value)
{
$sqlString .= '`'.$key.'`,';
$valueString .= '\''.htmlspecialchars($value).'\',';
}
$sqlString = rtrim($sqlString,',');
$valueString = rtrim($valueString,',');
$sqlString .= ') VALUES ('.$valueString.')"';
echo 'Received';
?>
Have fun!

Friday 6 June 2014

jQuery sticky plugin

The jQuery plugin below allows you to name an element as a sticky header or footer. You can also set the height, width and background colour. This is similar to those available in Twitter Bootstrap and ZURB Foundation.

First the HTML page:
<!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>jQuery sticky footer</title>
    <style>
    body
    {
      font:90%/1.6 sans-serif;
    }
    section
    {
      margin-top:6em;
    }
    </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/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <header>
      <h1>Hello, world!</h1>
    </header>
    <section>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac pretium velit. Morbi scelerisque vel risus sed ullamcorper. Integer nec dui vel magna malesuada tempus. Vivamus dictum elit sem, at mattis leo volutpat in. Phasellus felis metus, dapibus semper nisi non, sagittis lacinia erat. Fusce in diam et velit commodo rutrum in in dui. Sed imperdiet est non dui molestie consequat. Duis ac ipsum in purus tempor dictum. Curabitur ac neque sed sem semper congue. Pellentesque enim enim, congue sed consequat et, lobortis id tortor. Cras a faucibus sem. Mauris sed enim quam. Aenean sollicitudin posuere mauris. Curabitur sollicitudin orci orci, a sagittis neque feugiat nec.</p>
    </section>
    <footer>
      <p>Hello footer world!</p>
    </footer>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="sticky.plugin.js"></script>
    <script>
      /* Example parameters
      $('header').sticky(
      {
        position:'top',
        height:'10em',
        width:'50%',
        background:'red'
      });
      */
      $('header').sticky(
      {
        position:'top'
      });
      $('footer').sticky(
      {
        position:'bottom'
      });
    </script>
  </body>
</html>

Now the jQuery plugin, sticky.plugin.js
(function($)
{
$.fn.extend(
{
sticky:function(options)
{
var defaults =
{
position:'bottom',
height:'4em',
width:'100%',
background:'white'
}

var options = $.extend(defaults, options);

return this.each(function()
{
var o = options;
   $(this).css('position','fixed').css('_position','absolute').css(o.position,0).css('background',o.background);
   $(this).height(o.height);
   $(this).width(o.width);
       $(this).css('z-index', 9999);
});
}
});
})(jQuery);

Monday 12 May 2014

Introduction to the PHP5 Command Line Interface (Ubuntu version)

So you'd like to write and run your PHP5 code without using a web browser. Where you run it from the command-line....

First make sure that the php5 cli is installed by typing this on the command line (terminal, shell, whatever you want to call it) :

sudo apt-get install php5-cli

Now it's time to create your first command line script to test. Use your favourite editor to create the following program and save it as hello.php:

<?php
echo 'hello world!';
?>

Now back to the command line. Make sure you are in the same directory as hello.php was saved. Now type:
php5 hello.php

You should see that hello world! is echo'd to the command line.

Now the following program:

  • Takes the first number
  • Assigns it to a variable ($first)
  • Takes the second number
  • Assigns it to a variable ($second)
  • Adds the two numbers together and assigns them to the variable $answer
  • Echo's the value of the variable $answer, then adds a line break.


<?php
echo 'Enter first number ';
$first = fgets(STDIN);
echo 'Enter second number ';
$second = fgets(STDIN);
$answer = $first + $second;
echo 'And the answer is '.$answer.PHP_EOL;
?>

Now you're ready to go.

Tuesday 29 April 2014

jQuery equalise selector widths

Now for making the width of selectors the same. This gets slightly more complicated on 4 counts:
1. Firefox can't turn null values into zero, so you have to force it.
2. You also need to get margin, border and padding values to make your calculations. Including parent padding.
3. You have to handle the browser being resized.
4. You have to add a little contingency for browser rendering differences.
Let's start with the HTML:
<!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>equalise width</title>
    <link rel="stylesheet" type="text/css" href="style.css">  
    <!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <article>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliud igitur esse censet gaudere, aliud non dolere. Ad eos igitur converte te, quaeso. Atqui iste locus est, Piso, tibi etiam atque etiam confirmandus, inquam; Cum autem in quo sapienter dicimus, id a primo rectissime dicitur. Ut optime, secundum naturam affectum esse possit. Videsne quam sit magna dissensio? Duo Reges: constructio interrete. Sed quanta sit alias, nunc tantum possitne esse tanta. At enim hic etiam dolore. Facile est hoc cernere in primis puerorum aetatulis.</p>
    </article>
    <article>
      <p>Summus dolor plures dies manere non potest? At ego quem huic anteponam non audeo dicere; Nemo nostrum istius generis asotos iucunde putat vivere. Pugnant Stoici cum Peripateticis. Istam voluptatem perpetuam quis potest praestare sapienti? Quid sequatur, quid repugnet, vident.</p>
    </article>
    <article>
      <p>Nihil opus est exemplis hoc facere longius. Quam illa ardentis amores excitaret sui! Cur tandem? Sic enim censent, oportunitatis esse beate vivere.</p>
    </article>
    <footer>
      <p>footer</p>
    </footer>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>  
    <script src="equalisewidth.plugin.js"></script>
    <script>
    (function()
    {
      $('article').equalisewidth();
      $(window).resize(function()
      {
        $('article').equalisewidth();
      });
    })();
    </script>
  </body>
</html>
Now for the CSS (style.css):
body
{
  font: 90%/1.618 sans-serif;
  padding-top:2em;
}
article
{
float:left;
margin:1em;
padding:1em;
background:red;
color:white;
}
footer
{
clear:left;
}
And finally the jQuery plugin (equalisewidth.plugin.js):
(function($)
{
  $.fn.equalisewidth = function()
  {
    var thisMargin = parseInt($(this).css('margin-left').replace(/px/,'')) + parseInt($(this).css('margin-right').replace(/px/,''));
    if(isNaN(thisMargin)) thisMargin = 0;
    var thisBorder = parseInt($(this).css('border-left').replace(/px/,'')) + parseInt($(this).css('border-right').replace(/px/,''));
    if(isNaN(thisBorder)) thisBorder = 0;
    var thisPadding = parseInt($(this).css('padding-left').replace(/px/,'')) + parseInt($(this).css('padding-right').replace(/px/,''));
    if(isNaN(thisPadding)) thisPadding = 0;
    var thisParentPadding = parseInt($(this).parent().css('padding-left').replace(/px/,'')) + parseInt($(this).parent().css('padding-right').replace(/px/,''));
    if(isNaN(thisParentPadding)) thisParentPadding = 0;
    var equalWidth = $(this).parent().width() / $(this).length;
    var spacing = (thisMargin + thisParentPadding) + (thisBorder + thisPadding) + 2;
    var widthResize = equalWidth - spacing;  
    $(this).each(function()
    {
      $(this).width(widthResize);    
    });
  }
})(jQuery);
Enjoy!

jQuery equalise height plugin

Sometimes we just want a group of element to be the same height. It's more visually pleasing. This plugin is designed to do just that.
First the HTML:
<!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>equalise height</title>
    <link rel="stylesheet" type="text/css" href="style.css">  
    <!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <article>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliud igitur esse censet gaudere, aliud non dolere. Ad eos igitur converte te, quaeso. Atqui iste locus est, Piso, tibi etiam atque etiam confirmandus, inquam; Cum autem in quo sapienter dicimus, id a primo rectissime dicitur. Ut optime, secundum naturam affectum esse possit. Videsne quam sit magna dissensio? Duo Reges: constructio interrete. Sed quanta sit alias, nunc tantum possitne esse tanta. At enim hic etiam dolore. Facile est hoc cernere in primis puerorum aetatulis.</p>
    </article>
    <article>
      <p>Summus dolor plures dies manere non potest? At ego quem huic anteponam non audeo dicere; Nemo nostrum istius generis asotos iucunde putat vivere. Pugnant Stoici cum Peripateticis. Istam voluptatem perpetuam quis potest praestare sapienti? Quid sequatur, quid repugnet, vident.</p>
    </article>
    <article>
      <p>Nihil opus est exemplis hoc facere longius. Quam illa ardentis amores excitaret sui! Cur tandem? Sic enim censent, oportunitatis esse beate vivere.</p>
    </article>
    <footer>
      <p>footer</p>
    </footer>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="equaliseheight.plugin.js"></script>
    <script>
    (function()
    {
      $('article').equaliseheight();
    })();
    </script>
  </body>
</html>
Now the CSS (style.css):
body
{
  font: 90%/1.618 sans-serif;
  padding-top:2em;
}
article
{
float:left;
margin:1em;
padding:1em;
width:15em;
background:red;
color:white;
}
footer
{
clear:left;
}
And finally the jQuery plugin (equaliseheight.plugin.js):
(function($)
{
  $.fn.equaliseheight = function()
  {
    var maxHeight = 0;
    $(this).each(function()
    {
      if($(this).height() > maxHeight)
      {
        maxHeight = $(this).height();
      }
    });
    $(this).height(maxHeight);
  }
})(jQuery);