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);

Monday 28 April 2014

jQuery second word plugin

You've seen those fancy titles where the second word is a different colour from the first. To achieve this, you really don't want to have to put span tags all around your code. Below I've created a plugin which allows you to decide which elements have their second word looking different from the first. You can use it with any framework. Please excuse the separate CSS file, but I've been using LiveStyle with Sublime Text 2. It really speeds development up.
First the HTML:
<!DOCTYPE html>
<html lang="en">
  <head>  
    <title>Second word</title>  
    <link href='style.css' rel='stylesheet' type='text/css'>  
  </head>
  <body>
    <header>
      <h1>Second word</h1>
    </header>
    <section>
      <article>
        <h2>Sub header</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sin tantum modo ad indicia veteris memoriae cognoscenda, curiosorum. Si verbum sequimur, primum longius verbum praepositum quam bonum. Duo Reges: constructio interrete. Falli igitur possumus. Egone non intellego, quid sit don Graece, Latine voluptas? Sed virtutem ipsam inchoavit, nihil amplius. Sed eum qui audiebant, quoad poterant, defendebant sententiam suam.</p>
      </article>
      <article>
        <h2>Sub heading</h2>
        <p>Quis est, qui non oderit libidinosam, protervam adolescentiam? Nam si amitti vita beata potest, beata esse non potest. Recte, inquit, intellegis. Idemne potest esse dies saepius, qui semel fuit? Venit enim mihi Platonis in mentem, quem accepimus primum hic disputare solitum; Aliter enim explicari, quod quaeritur, non potest. Profectus in exilium Tubulus statim nec respondere ausus; Nos vero, inquit ille;</p>
      </article>        
    </section>
    <footer><p>&copy; Second word 2014</p></footer>  
    <script src="https://code.jquery.com/jquery.js"></script>
    <script src="secondword.plugin.js"></script>
    <script>
    (function()
    {
        $('header > h1, article > h2').secondword();
    })();
    </script>
  </body>
</html>

Now the style.css:
body
{
padding:1em;
font-family:Sans-serif;
}
header, footer, article > h2
{
font-family:Serif;
color:red;
font-style:italic;
}
section > article
{
text-align:justify;
line-height:1.7;
}
body, header > h1 span.secondword, article > h2 span.secondword
{
color:#777;
}

And finally, the jQuery plugin, secondword.plugin.js:
(function($)
{
  $.fn.secondword = function()
  {
    $(this).each(function()
    {
      var text = $(this).text().split(' ');
      if(text.length < 2) return;
      text[1] = '<span class="secondword">'+text[1]+'</span>';
      $(this).html(text.join(' '));
    });
  }
})(jQuery);

Friday 25 April 2014

Get .htaccess files working on Ubuntu after LAMP installation

Step 1. Configure Apache mod_rewrite
sudo a2enmod rewrite

Step 2. Within the file /etc/apache2/apache2.conf
Under the section labelled <Directory /var/www/>
Change the line
AllowOverride None
to
AllowOverride All

Step 3. Restart apache
sudo /etc/init.d/apache2 restart