Posts

Home PHP

Apache .htaccess RewriteRule Examples with PHP for Clean URLs

Our code for today will make your website URLs clean and attractive. Clean URLs are user and SEO friendly, it does not contain any query string like:

…page.php?param1=something&id=1111

Thus, giving our users and search engines (like Google) an idea what your link is all about once it was shared to social media or indexed by Google or Bing.

.htaccess rewriterule examples - first example is smashing magazine

We are going to use .htaccess (hypertext access) rewrite rules to achieve these clean URLs. The .htaccess file provide a directory level configuration that is supported by several web servers such as Apache.

Our post for today covers the following contents:

1.0 Existing Apache .htaccess Rewriterule Examples

2.0 Four Apache .htaccess Rewriterule Example Codes
2.1 URL with two parameters: letter and number
2.2 URL with one parameter: name of the PHP file
2.3 URL with one parameter: numbers
2.4 URL with one parameter: numbers with underscore

3.0 Complete .htaccess Code Used
4.0 Apache .htaccess RewriteRule Resources

1.0 Existing or Live Apache .htaccess Rewriterule Examples

Below are other example websites with clean URLs.

Of couse you know this blog, don't you?

Of couse you know this blog, don’t you? :))

Chris' blog

Chris’ blog

David’s blog

David’s blog

2.0 Four Apache .htaccess Rewriterule Examples

Our .htaccess and PHP files are placed in the “htaccess-clean-urls” folder.

.htaccess uses regular expressions to identify which PHP file will be loaded on the browser, based on the parameter(s) given.

We have 4 example codes below. Please note that “localhost” refers to “yoursite.com”. I was using my local server when I did these examples so please keep it in mind.

2.1 URL with two parameters: letter and number

This URL:

http://localhost/htaccess-clean-urls/parameter_letter_and_number.php?param=post¶m2=143

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/post/143

.htaccess code used:

RewriteRule ^([a-z]+)\/([0-9]+)\/?$ parameter_letter_and_number.php?param=$1&param2=$2 [NC]

PHP page used: parameter_letter_and_number.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Clean URL with .htaccess by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Parameter: Letter and Number ONLY. This is parameter_letter_and_number.php</h1>
<?php 
echo "PARAMETER VALUE 1: " . $_REQUEST['param'];
echo "<br />";
echo "PARAMETER VALUE 2: " . $_REQUEST['param2'];
?>

</body>
</html>

Output screenshot:

.htaccess RewriteRule Example - parameter and number

2.2 URL with one parameter: name of the PHP file

This URL:

http://localhost/htaccess-clean-urls/login.php
http://localhost/htaccess-clean-urls/register.php

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/login/
http://localhost/htaccess-clean-urls/register/

.htaccess code used:

RewriteRule ^([a-z]+)\/?$ $1.php [NC]

PHP pages used:

login.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>login - Clean URL tutorial with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Login. This is login.php</h1>

</body>
</html>

register.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>register - Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Register. This is register.php</h1>

</body>
</html>

Output Screenshots:

login page clean url

register page rewriterule example

2.3 URL with one parameter: numbers

This URL

http://localhost/htaccess-clean-urls/parameter_number.php?param=5254

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/5254/

.htaccess code used:

RewriteRule ^([0-9]+)\/?$ parameter_number.php?param=$1 [NC]

PHP page used: parameter_number.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>parameter is number - Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Parameter: Number ONLY. This is parameter_number.php</h1>
<?php echo "PARAMETER VALUE: " . $_REQUEST['param']; ?>

</body>
</html>

Output Screenshot:

htaccess rewriterule number example

2.4 URL with one parameter: numbers with underscore

This URL:

http://localhost/htaccess-clean-urls/parameter_number_and_underscore.php?param=143_5254

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/143_5254/

.htaccess code used:

RewriteRule ^([0-9_]+)\/?$ parameter_number_and_underscore.php?param=$1 [NC]

PHP page used: parameter_number_and_underscore.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>parameter is number and underscore- Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Parameter: Number and Underscore ONLY. This is parameter_number_and_underscore.php</h1>
<?php echo "PARAMETER VALUE: " . $_REQUEST['param']; ?>

</body>
</html>

Output Screenshot:

htaccess rewriterule example - number and underscore

3.0 Complete .htaccess Code Used

The following codes are the ones we used in the examples above, put into one .htaccess file.

<IfModule mod_rewrite.c>

    RewriteEngine on

    RewriteRule ^([a-z]+)\/([0-9]+)\/?$ parameter_letter_and_number.php?param=$1&param2=$2 [NC]
    
    RewriteRule ^([a-z]+)\/?$ $1.php [NC]
    
    RewriteRule ^([0-9]+)\/?$ parameter_number.php?param=$1 [NC]
    
    RewriteRule ^([0-9_]+)\/?$ parameter_number_and_underscore.php?param=$1 [NC]
    
</IfModule>

4.0 .htaccess RewriteRule Resources

If you want to learn more, here’s a mod_rewrite or regex cheat sheet.
An In Depth Guide to mod_rewrite for Apache
Apache mod_rewrite

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

If you have some questions or want to add more Apache .htaccess RewriteRule examples, please drop it in the comments section below! I will update this post once you did, thanks for your contribution!

Home jQuery

Two Example Usage of jQuery On() Method

How are you guys? Many friends asks me what is the use of jQuery on() method, where and when can we use it and why is it important. So in this tutorial, I’m going to give you two example situations where we can use the jQuery on() method.

Home>jQuery Two Example Usage of jQuery On() Method

Loading and submitting a from without page refresh.

By definition, jQuery on() method attaches an event handler function (click, submit, etc.) to one or more elements (div, p, etc.). In my experience, I used jQuery on() when:

  • I want to load a new HTML form on a DIV and submit it without page refresh.
  • I want to reload a list of records and use the actions like ‘Delete’.

By the way, you can download all the codes used in this post:

Loading Different Forms to a DIV

This code can load the ‘Add User’ and ‘Add Role’ form to the ‘formContainer’ DIV (one at a time). Our goal is to submit the form without page refresh. To achieve that we are going to use the on() method. See the live demo:

form_w_on.php code:

<html>
    <head>
        <title>jQuery On() Tutorial - submit with on()</title>
    
        <style>
        #addNewUser, #addNewRole{
            cursor:pointer;
            float:left;
            text-decoration:underline;
        }
        
        #formContainer{
            border:thin solid #000;
            padding:0.5em;
            margin:1em 0 0 0;
        }
        
        .clearBoth{
            clear:both;
        }
        </style>
        
    </head>
<body>

<div id='addNewUser'>[+ New User]</div>
<div id='addNewRole'>[+ New Roles]</div>

<div class='clearBoth'></div>

<div id='formContainer'>
    <!--here is where the form will be loaded -->
</div>

<script src='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){

    // when user clicks '[+ New User]', it will load the add_user.php file
    $('#addNewUser').click(function(){
        
        $('#formContainer').load('add_user.php', function(){
            console.log('user form loaded!');
        });
        
    });
    
    // when user clicks '[+ New Roles]', it will load the add_role.php file
    $('#addNewRole').click(function(){
        $('#formContainer').load('add_role.php', function(){
            console.log('role form loaded!');
        });
    });
    
    // when the user submits the 'add new user' form
    $(document).on('submit', '#addUserForm', function(){ 
        alert('Add new user form is submitted!');
        return false;
    });

    // when the user submits the 'add new role' form
    $(document).on('submit', '#addRoleForm', function(){ 
        alert('Add new role form is submitted!');
        return false;
    });
    
    
});
</script>

</body>
</html>

add_user.php code:

<form id='addUserForm'>
    <div>Firstname: <input type='text' name='firstname' /></div>
    <div>Lastname: <input type='text' name='lastname' /></div>
    <div><input type='submit' value='Save' /></div>
</form>

add_role.php code:

<form id='addRoleForm'>
    <div>User Role: <input type='text' name='role' /></div>
    <div>Description: <input type='text' name='description' /></div>
    <div><input type='submit' value='Save' /></div>
</form>

Without the on() method, jQuery code usually looks like this (form_w_out_on.php):

<script>
$(document).ready(function(){

    // when user clicks '[+ New User]', it will load the add_user.php file
    $('#addNewUser').click(function(){
        
        $('#formContainer').load('add_user.php', function(){
            console.log('user form loaded!');
        });
        
    });
    
    // when user clicks '[+ New Roles]', it will load the add_role.php file
    $('#addNewRole').click(function(){
        $('#formContainer').load('add_role.php', function(){
            console.log('role form loaded!');
        });
    });
    
    // when the user submits the 'add new user' form
    $('#addUserForm').submit(function() {
        alert('Add user form is submitted!');
        return false;
    });

    // when the user submits the 'add new role' form
    $('#addRoleForm').submit(function() {
        alert('Add new role form is submitted!');
        return false;
    });
    
});
</script>

Here’s a live demo without using the on() method, it reloads the whole page.

Loading Table List to a DIV

jquery-on-tutorial---load-table-list

In this example, when the user clicks on the “[Load List]” text, it will load a table list of data (list.php) with a ‘Delete’ action right across each records.

index.php code:

<html>
    <head>
        <title>jQuery on() tutorial - loading lists</title>
        
        <style>
        #myTable{
            float:left;
            margin:1em 0 0 0;
        }
        
        #myTable th, 
        #myTable td{
            border:thin solid #000;
            padding:1em;
        }
        
        .deleteAction{
            cursor:pointer;
        }
        
        #loadAction{
            cursor:pointer;
            text-decoration:underline;
        }
        </style>
        
    </head>
<body>

<div id='loadAction'>[Load List]</div>

<div id='listContainer'>
    <!--here is where the form will be loaded -->
</div>

<script src='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){

    $('#loadAction').click(function(){
        
        $('#listContainer').load('list.php', function(){
            console.log('list loaded!');
        });
        
    });
    
    /*
    // using this code won't pop up 'Are you sure?'
    $('.deleteAction').click(function(){
        if(confirm('Are you sure?'){

             // do things if ok

        }
    });
    */
    
    $(document).on('click', '.deleteAction', function(){ 
        if(confirm('Are you sure?')){

             // do things if ok

        }
    });
    
});
</script>


</body>
</html>

Similarly, as indicated in the code comments, ‘Are you sure?’ alert dialog won’t be shown without the help of the jQuery on() method.

list.php – the data to be loaded in the listContainer div.

<table id='myTable'>
    <tr>
        <th>Name</th>
        <th>Action</th>
    </tr>
    <tr>
        <td>Mike Dalisay</td>
        <td>
            <div class='deleteAction'>Delete</div>
        </td>
    </tr>
    <tr>
        <td>Marykris De Leon</td>
        <td>
            <div class='deleteAction'>Delete</div>
        </td>
    </tr>
</table>

There are other previously used methods almost similar the jQuery on(), like live() and delegate(). But among those methods, jQuery on() is recommended to use (if you’re using jQuery 1.7+). Users of older versions of jQuery should use delegate() in preference to live().

If you want to read more about this topic,here are some links that can help.

Download Source Codes
You can download all the code used in this tutorial for only $9.99 $5.55!

Home jQuery

A Quick Way To Create A Vertical Accordion With jQuery

jquery-tutorial

Today we are going to create a vertical accordion from scratch, using jQuery of course! We will have few lines of code that would be easy to understand. I used this code when I was asked to create an accordion for a website’s headlines.

A Quick Way To Create A Vertical Accordion With jQuery

So in this example code, we will have:

  • Three headlines, one headline is opened on load by default.
  • When a use clicks on a headline with hidden content, it will slide down the hidden content to be shown and close (slide up) the previously opened headline.

CSS – You may do your tweaks to design your own accordion (change colors, add images, etc.) but make sure the main style are the following.

body {
    font-family:Georgia, serif;
}

.headlineTitle {
    font-weight:bold;
    padding:5px 0;
}

.item {
    border:thin solid #c0c0c0;;
    margin:0 0 0.5em 0;
}

.itemContents {
    display:none;
    margin:.05em 0 0 0;
    padding:10px;
}

.itemTitle {
    background-color:#FAEBD7;
    cursor:pointer;
    font-weight:bold;
    padding:10px;
}

.openedContent {
    display:block;
}

HTML – Our html scructure would look like this. This could be generated multiple times by your server side script like PHP (reading records from a database), but in this example, we are using static HTML.

<div class="itemsContainer">
<div class="item">
    <div class="itemTitle opened">First Headline</div>
    <div class="itemContents openedContent">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
    </div>
</div>
<div class="item">
    <div class="itemTitle">Second Headline</div>
    <div class="itemContents">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
    </div>
</div>

jQuery – makes our accordion work with few lines of codes.

$('.itemTitle').click(function () {

    // show the content only if it is hidden        
    if ($(this).closest('.item').find('.itemContents').is(":hidden")) {
    
        //open the content          
        $(this).closest('.item').find('.itemContents').slideDown("fast");
        
        //close previously opened content           
        $(this).closest('.itemsContainer').find('.opened').closest('.item').find('.itemContents').slideUp("fast");
        
        // remove the "opened" class from previously opened content         
        $(this).closest('.itemsContainer').find('.opened').removeClass('opened');
        
        //add class to mark the clicked item is opened          
        $(this).addClass("opened");
    }
});

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

How To Get Facebook App ID and Secret Keys?

After creating a Facebook page where we will pull our data, we have to create an app to get an appId and appSecret keys. Those keys are required to use the Facebook PHP SDK and do our queries like pulling Facebook photos, events, videos, and feeds. Here’s a step by step tutorial on how to get those keys.

How To Get Facebook App ID and Secret Keys?

Facebook developer apps dashboard.

Step 1

Here’s the link where you would start: create a Facebook app. On the pop up, specify your app name (the name of your website or app) and app namespace (used for your Facebook app URL e.g., http://apps.facebook.com/yournamespace)

Creating an app.

Creating an app.

Step 2

You’ll be asked to enter a security code to verify that you’re a human and not a bot or malware that creates random Facebook apps. After entering the text in the box, click the “Continue” button.

A security check.

A security check.

Step 3

Congrats! now you can copy your Facebook appId and appSecret. See the arrows below.

Your Facebook appId and appSecret keys.

Your Facebook appId and appSecret keys.

Step 4

Prepare your App ID and App Secret keys, we’ll use it to get your access token, here’s how:

https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials

Replace YOUR_APP_ID and YOUR_APP_SECRET with your own and run the link on the browser.

Home Facebook

How Do You Start A Facebook Page?

Hi guys! Most of the top posts here in my blog is related to web development with Facebook. Many asks beforehand how to create a Facebook page where we will pull our data. So here’s a step by step tutorial on how to do such task.

How Do You Start A Facebook Page?

Our final output.

Photos are kinda small, you have to click each photos below to enlarge.

Step 1

Go to Facebook “Create A Page” section that can be found in this link: Create a Page. You should see this page:

Create a Facebook page.

Create a Facebook page.

Step 2

In this example, we are going to create a “Brand or Product” for our website. Click “Brand or Product” box and fill up the required filled.
On the “Category” dropdown, select “Website”.
On the “Brand or Product Name” field, I’ll enter “Mike Dalisay Works” for example.
Check “I agree to Facebook Pages Terms” checkbox.
It should look like this:

Creating a brand or product Facebook page.

Creating a brand or product Facebook page.

Step 3

Click the “Get Started” button. It will make you set up some information for your Facebook page such as profile picture, about, Facebook web address, and enable ads option. Just follow the flow.

Facebook page info set up.

Facebook page info set up.

Facebook page profile picture.

Facebook page profile picture.

Facebook page “About” info

Facebook page “About” info

Facebook web address.

Facebook web address.

Enable ads. You can click the skip button.

Enable ads. You can click the skip button.

Step 4

At this stage, you already have successfully created your Facebook page! Congrats! Now Facebook will give you some guidelines on how to use your Facebook page.

Like your own page.

Like your own page.

Invite others to like your page.

Invite others to like your page.

Do your first post!

Do your first post!

Home Lists+

How To Make Responsive Web Design CSS Code?

In today’s tutorial, I’m going to show you a systematic and very simple way to create a responsive website with CSS3 media queries and HTML5. Responsive web design has been around for few years now and is widely accepted as a new standard when building a modern website.

Coding A Responsive Website Design

For the “live demo”, please try to resize your browser to see the page’s responsiveness.

I want to give you a brief definition of what a responsive web design is, if you already know what it is, you may skip this part and jump to the “Let’s code” section below. Well, for me, responsive web design is a way to show your web site’s content in an easy-to-understand manner regardless of what device views it.

For example, a visitor of your website must feel comfortable when viewing the same website for any type of devices (with different screen sizes) he has. Example of those devices include:

  • Android phones
  • iPhones
  • 7″ tablets
  • 10″ tablets
  • iPads
  • Desktop computers
  • and many more devices that can view a web page.

Other points to consider…

  • Your website should not have a horizontal scrollbar.
  • Users must not use the zoom tool to view your site’s contents.

By the way, if you want to test the live demo on different devices easily, you can use the tools described on this link: Responsive Web Design Testing Tools.

Let’s code.

Step 1: It is important to build your website for the smallest device possible first. Build the website for smart phones. You can view a live demo of our step 1 here.

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
         
          <title>Your Website</title>
         
          <style>
              
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
         
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
         
          .media1140px{
               background-color:#CE9429;
          }
         
          .media768px{
               background-color:#EDD49A;
          }
         
          .media480px{
               background-color:#EFEF34;
          }
         
          .media300px{
               background-color:#82EAFF;
          }
         
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
         
          p{
               margin:0 0 20px 0;
          }
         
          .clearb{
               clear:both;
          }
          /* misc end */
         
         
         
         
         
         
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
          
          /* to make our logo resize automatically */
          #responsiveLogo{
               width:100%;
          }
         
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
         
         
         
         
         
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
         
          nav ul{
               list-style-type:none;
               padding:0;
          }

          nav ul li{
         
          }

          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
         
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
         
         
         
         
         
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
         
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
         
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
         
         
         
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
              
          </style>
         
     </head>
<body>

     <header id='mainHeader'>
    
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
    
     <section id='mainSection'>

          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>

     </section>

     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>

     <div class='clearb'></div>
    
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>

</body>
</html>

After doing the code above, our webpage is not yet responsive. You won’t see the magic even if you resize your browser. By the way, you can also include the CSS code as external file.

Step 2: Now let’s create the website layout for a type of device next to a smart phone, maybe we can consider a 7″ tablets as one. You can view a live demo of your step 2 here.

We’ll just add the following CSS:

/* 
-can be for 7 inch tablets
-This CSS will apply for devices with the minimum width of 480 pixels
 */
@media only screen and (min-width: 480px) {
     #mainHeader {
          background-color:#EFEF34;
     }
    
     nav ul li{
          float:left;
          width:25%;
     }
}

Now if you’ll resize your browser, you can see that your website is already responsive in two ways.

Step 3: Now we will create the website layout for another type of screen next to 7″ tablets, we can consider the iPad or 10″ tablets in portrait mode. Our step 3 live demo is here.

Please add the following CSS:

/*
-10 inch tablets
-This CSS will apply for devices with the minimum width of 768 pixels
*/
@media only screen and (min-width: 768px) {
     #mainHeader {
          background-color:#EDD49A;
     }
    
     #mainSection{
          float: left;
          width: 61%;
     }
    
     #sideBox1{
          float: right;
          width: 30%;
     }
    
}

Now our website is responsive in three ways. Try to re-size your browser again.

Step 4: Now we will create the website for desktop computers, laptops or 10″ tablets in landscape mode.

/*
-Desktop computers
-This CSS will apply for devices with the minimum width of 1140 pixels
*/
@media only screen and (min-width: 1140px) {
     #mainHeader {
          background-color:#CE9429;
     }
    
     #responsiveLogo{
          float:left;
          width:30%;
     }
    
     nav{
          float:left;
          width:70%;
     }
    
     nav ul{
          margin:1.5em 0 0 0;
     }
}

Complete web page code:

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
         
          <title>Your Website</title>
         
          <style>
              
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
         
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
         
          .media1140px{
               background-color:#CE9429;
          }
         
          .media768px{
               background-color:#EDD49A;
          }
         
          .media480px{
               background-color:#EFEF34;
          }
         
          .media300px{
               background-color:#82EAFF;
          }
         
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
         
          p{
               margin:0 0 20px 0;
          }
         
          .clearb{
               clear:both;
          }
          /* misc end */
         
         
         
         
         
         
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
         
          #responsiveLogo{
               width:100%;
          }
         
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
         
         
         
         
         
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
         
          nav ul{
               list-style-type:none;
               padding:0;
          }

          nav ul li{
         
          }

          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
         
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
         
         
         
         
         
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
         
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
         
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
         
         
         
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
         
         
         
         
         
         
         
          /* @media start */
         
          /* we don't need to specify for smartphones, that's our default layout */
         
          /*
          -7 inch tablets
          -This CSS will apply for devices with the minimum width of 480 pixels
          */
          @media only screen and (min-width: 480px) {
               #mainHeader {
                    background-color:#EFEF34;
               }
              
               nav ul li{
                    float:left;
                    width:25%;
               }
          }
         
          /*
          -10 inch tablets
          -This CSS will apply for devices with the minimum width of 768 pixels
          */
          @media only screen and (min-width: 768px) {
               #mainHeader {
                    background-color:#EDD49A;
               }
              
               #mainSection{
                    float: left;
                    width: 61%;
               }
              
               #sideBox1{
                    float: right;
                    width: 30%;
               }
              
              
          }
         
          /*
          -Desktop computers
          -This CSS will apply for devices with the minimum width of 1140 pixels
          */
          @media only screen and (min-width: 1140px) {
               #mainHeader {
                    background-color:#CE9429;
               }
              
               #responsiveLogo{
                    float:left;
                    width:30%;
               }
              
               nav{
                    float:left;
                    width:70%;
               }
              
               nav ul{
                    margin:1.5em 0 0 0;
               }
          }
         
          /* @media end */
              
          </style>
         
     </head>
<body>

     <header id='mainHeader'>
    
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
    
     <section id='mainSection'>

          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>

     </section>

     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>

     <div class='clearb'></div>
    
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>

</body>
</html>

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Some screenshots of our output:

Page header smartphone screenshot – landscape mode

Page header smartphone screenshot – landscape mode

Footer screenshot from my smartphone in landscape mode.

Footer screenshot from my smartphone in landscape mode.

Header screenshot from my smartphone  in portrait mode.

Header screenshot from my smartphone
in portrait mode.

Body section screenshot from my Smartphone in  portrait mode.

Body section screenshot from
my Smartphone in portrait mode.

Footer screenshot from  my smartphone in portrait mode.

Footer screenshot from
my smartphone in portrait mode.

Screenshot from my 10.1 Android tablet in portrait mode.

Screenshot from my 10.1 Android tablet in portrait mode.

Credits: Image from Game Note.

Home Lists+

JavaScript Array CRUD Example

Our code for today will give us example on how to Create, Read, Update and Delete (CRUD) items in a JavaScript array. This technique will give you full control over the fields and values of each array item.

Example use of this code is when you have long rows of input elements and wanted to detect only the elements with inputted values, get their id, value and other related information. You won”t have to loop through all the input elements to check if there are inputted values.

This is because, you can instantly add an item to the array if the value was inputted, edit it when the value were changed, delete it when the value were removed and then read it for posting or later use. We can achieve better performance. Here is a video demo:

JavaScript Crud Example

Our index.php code – here you can see the our JavaScript CRUD functions (with some jQuery help) and sample HTML.

<html>
    <head>
        <title>JS Array CRUD - https://codeofaninja.com</title>
    </head>
   
<body>

<!–
    -example row of items
    -id is the item number
    -common class name
–>
Item 1 <input type="text" id="1" class="item" /><br />
Item 2 <input type="text" id="2" class="item" /><br />
Item 3 <input type="text" id="3" class="item" /><br />
Item 4 <input type="text" id="4" class="item" /><br />
Item 5 <input type="text" id="5" class="item" /><br />

<br />
<br />

<!– display the operations here –>
<b>Actions:</b>
<div id="status"></div>

<br />

<!– display the array length and items –>
<b>All Items:</b>
<div id="results"></div>

</body>
</html>

Now, put the following code before the closing body tag of our HTML code above.

<!– include the jquery –>
<script type="text/javascript" src="jquery.min.js"></script>

<script type="text/javascript">
    // initialize array as global variable
    var items = [];
   
    $(document).ready(function(){
   
        //we use the jquery blur event
        $(".item").blur(function(){
       
            //in this example, the item id is the id attribute of the element
            var item_id = $(this).attr("id");
           
            //item value is the inputtedvalue
            var item_value = $(this).val();
           
            //then process the item
            process_item(item_id,item_value);
        });
       
    });
   
    // ———— functions [START] ————

    // process item, usually based in item id
    function process_item(item_id,item_value){
       
        if(item_value==""){
            //if item value is empty, delete from the array
            delete_item(item_id);
        }else if(checkIfExists(item_id)){
            //search if item_id exists in the array
            //if item exists, edit it
            edit(item_id,item_value);
        }else if(!checkIfExists(item_id)){
            //if item does not exist, add it
            add(item_id,item_value);
        }
       
        //read the items
        showAllItems();
    }
   
    // ADD
    function add(item_id,item_value){
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("Successfully added.");
    }

    // EDIT
    function edit(item_id,item_value){
       
        //delete first
        items.remove("item_id", item_id);
       
        //then add again
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("successfully edited.");
           
    }
   
    // DELETE
    function delete_item(item_id){
        items.remove("item_id", item_id);
        $("#status").text("Successfully deleted.");
    }
   
    // READ
    function showAllItems(){
       
        //clear results text
        $("#results").text("");
       
        var arr_len = items.length;
       
        // display also the array length
        $("#results").append("Array len: " + arr_len+ "<br />");
       
        //loop through the array to read the items
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
           
            //append to results div to display
            $("#results").append("item_id: " + item_id + " >>> item_value: " + item_value + "<br />");
        }
    }
   
    function checkIfExists(check_item_id){
       
        //get the array length first
        var arr_len = items.length;
       
        //search the array
        //there might be another way
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
           
            if(check_item_id==item_id){
                //it means the item exists
                return true;
            }
        }
       
        return false;
    }
   
    //needs a remove function
    Array.prototype.remove = function(name, value) {
        array = this;
        var rest = $.grep(this, function(item){
            return (item[name] != value);  
        });

        array.length = rest.length;
        $.each(rest, function(n, obj) {
            array[n] = obj;
        });
    };
    // ———— functions [END] ————
</script>

Convert to JSON

You can also convert the array to a JSON this way:

Add the json2.js file from here.

<script type="text/javascript" src="json2.js"></script>

…and do this

var json_str= JSON.stringify(items);

Posting the Array

If you want to post the resulting array..

1. Prepare the PHP file that will receive the post value. I created get_post.php with the code:

<?php
//just to display raw values
echo "<pre>";
    print_r($_POST);
echo "</pre>";

//access the values
foreach($_POST['items'] as $item){
    echo $item['item_id'] . ":" . $item['item_value'] . "<br />";
}
?>

2. Add a button and a new div area to our index.php

The button:

<input type="button" value="Post Array" id="post" />

Div area where we can see the posted values..

<!– display the posted items value –>
<b>Posted Items:</b>
<div id="postedItems"></div>

3. Clicking the post array button will show the posted value to postedItems div.

$("#post").click(function(){
    $.ajax({
        url: "get_post.php",
        data: {"items": items},
        type: "post",
        success: function(data) {
            $("#postedItems").append(data);
        }
    });
});

The value posted to get_post.php look like this:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [item_id] => 1
                    [item_value] => john
                )

            [1] => Array
                (
                    [item_id] => 3
                    [item_value] => michael
                )

        )

)

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Thank you for learning from our post about: JavaScript CRUD example!

Cron Job Example with PuTTy

Today we are going to run a PHP script on schedule, in other words, this PHP script should be executed in certain period of time. This could be any script you want, it can be used to send email to your users, make changes to your file system or database, crawl a website, etc. Running a script on schedule has a lot of benefits because it does the job automatically, without you worrying about it.

Cron Job Example with PuTTy

Execute a program via command line

We’re gonna be able to achive this using:

  1. PuTTy – a secure shell or terminal emulator used to access remote systems over the internet.
  2. Cron – the time based job scheduler in unix-like operating systems which powers most servers today.
  3. cURL – a command line tool for getting and sending files using URL syntax. This is usually installed already in your server.

You can skip step 1, 2 and 3 if you know how to log in using PuTTy.

Step 1
If you don’t have PuTTy in your computer, you can download it here, choose putty.exe if you’re on windows.
Step 2
Run putty.exe, it will look like this:

Cron Job Example with PuTTy

  • Arrow # 1 is where you’re gonna put your host name or IP address of your server.
  • Arrow # 2 is the button you’re gonna click (or you can simply press enter) immediately after entering your server host name of IP address.

Step 3
You’ll be asked to enter your server username and password. It looks like this:

2

Step 4
You should be in the crontab, type: crontab -e and press enter. By the way, a crontab is a simple text file in your server with a list of commands meant to be run at specified times, more info here.

3

It will list the the cron jobs (not yet editable)

4

Step 5
To make it editable, you should press the “insert” button on your keyboard.

5

Now you can edit your cron jobs or schedules, there are so many tutorials on how to construct a cron job, you can find some here and here.

On my example above, the cron runs two php script every one minute via cURL. A brief explanation:

#  MIN  HOUR  MDAY  MON  DOW  COMMAND
*/1   *   *   *   *   curl http://mydomain.com/myphp_script.php

MIN – Minute 0-60
HOUR – Hour [24-hour clock] 0-23
MDAY – Day of Month 1-31
MON – Month 1-12 OR jan,feb,mar,apr…
DOW – Day Of Week 0-6 OR sun,mon,tue,wed,thu,fri,sat
COMMAND – Command to be run Any valid command-line

Step 6
After you’re done editing, press the “Esc” key on your keyboard to exit from the edit mode. It will again look like this:

4

Step 7
To exit cron tab, you should type: :wq and press enter.

6

Then it will look like this:

8

That’s it! Our PHP scripts will be executed every one minute!