Saturday, November 21, 2015

Instant Image Preview in the Browser using JQuery

We can set an image element(<img/>)'s value with that of an image we just selected from a file input instantly(without uploading to server) using JQuery.

Suppose we have a form:
<form id="sample_form">
     Photo: <input type="file" id="photo"/>
     <img id="photo_preview" src="#" width="200px"/>
</form>


In order to read the input image and display it in the '<img/>' element, we need to bind the '<input />' element's  '.change' event with a custom JQuery function :
<script>
     $("#photo").change(function(){
         read_file(this);
     });
</script>


Now the function read_file() can be written like this:
function read_file(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
         reader.onload = function (e) {
            $('#photo_preview').attr('src', e.target.result);
         }
         reader.readAsDataURL(input.files[0]);
    }
}

Here is the complete code:
image_preview.html
<!DOCTYPE html>
<html>
 <head>
  <title>Image Preview</title>
  <meta charset="utf-8">
 </head>
 <body>
  <div class="container">
    <form id="sample_form">
       Photo: <input type="file" id="photo"/>
       <img id="photo_preview" src="#" width="200px"/>
    </form>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script>
   function read_file(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#photo_preview').attr('src', e.target.result);
          }
        reader.readAsDataURL(input.files[0]);
      }
    }
  </script>
  <script>
     $("#photo").change(function(){
         read_file(this);
     });
  </script>
 </body>
</html>
Now whenever you browse and select an image, it will be shown instantly in the browser.

Thursday, November 19, 2015

Custom routing in CodeIgniter

We can add custom routing urls in CodeIgniter.
Just open application/config/routes.php and edit the entries which you need to modify.
This file contains the routes array which redirects us to the different urls.

We can change the actual routing url to anything we like.
For example suppose I have a controller named 'pages' with a function 'show' to serve the pages to the user. So normally, calling 'index.php/pages/show' will be the working url which serve a page. It can be changed to anything you wish like index.php/showThePage which still work like the above url.
To do that, just add the following in routes.php:
$routes['showThePage'] = 'pages/show';
The entry inside the routes array will direct the user to the actual url without showing the actual url.

Sunday, November 15, 2015

Ponmudi in the evening

It was a bored-to-the-hell sunday and so called Sandeep and decided to take a spin. The time was around 4 pm evening,  with non-stop raining and a frightening dark sky, which was perfect! Riding in the rain is something which I love so much so whenever it rains I don't stop instead just ride on, except for the morning commute to office! Decided Ponmudi as the destination because it will be damn refreshing to spent time in hills in late evening. This was my fourth time in Ponmudi but it was totally different from others coz it's a rainy day, the way is pretty foggy and the roads are in slippery condition as well, so it was a challenge to reach the hill top. Clearing the 22 hairpins was a pure bliss and ofcourse scary in such conditions and the grippy michelins never let me down. Took stops at 3 points on the way to enjoy the views, hill sides and valleys.
This is the trekking trail to Braemore hillstation from the top of Ponmudi

The views were damn awesome in the evening coupled with rain clouds and mist. Enjoyed the pure misty atmosphere and continued and reached the checkpost. The funny part was we reached there at 5.50pm, the ticket counter closed at 5.30 and they were about to leave. At first they didn't allowed to enter but after some strong persuasion they allowed and opened the gate, reached the hilltop at 6 pm. Normally Ponmudi is a crowded place, many people will be there to walk and enjoy the sceneries but at this time there was none except for a few people here and there. Parked the bike and walked to the view points. I know the beauty of  Ponmudi at day time but it's a different experience to view Ponmudi at evening, late evening to be precise.
The hills touched by the clouds

The hills touched by the clouds and sweeping valleys in a rainy mood are a visual treat! Dark rain clouds further added some contrast and horror feel to the atmosphere altogether.
A panorama of Ponmudi hillstation

Clicked some photos and left at 7 pm when the light became too low. The downhill ride was even more adventurous since there was 22 hairpin curves in night and that too in foggy atmoshere!
Creepy evening atmosphere at Ponmudi

So guys if you haven't yet visited here, it will be a huge miss so plan a trip to this hillstation. And those who haven't visited here in the evening, it's a totally different atmosphere in evening, I'm sure you will love it. 

Wednesday, November 11, 2015

Data attribute in html and setting multiple data-* attributes in JQuery

Have you heard of data attribute in HTML? Well, it's a very handy attribute in developing web applications. We can easily bind custom data to any element in the DOM using the data attribute. This custom data can then be easily fetched using JQuery.

Suppose we have a link like this
<a id="show_data" data-category="Student" data-name="John" data-semester="sixth" href="#" >Show Data</a>
Now we can extract the data in JQuery like this
$("#show_data").click(function() {
         var name = $(this).data("name");
         var category = $(this).data("category");
         var semester = $(this).data("semester");
         alert(name + ", " + category + ", " + semester);
});

Now the reverse, suppose you have a link element or any element and want to set data attribute(not just data, you can set any attribute too) using JQuery
<a href="#" id="our_link">Our link element</a>

$(document).ready(function() {
         $("#our_link).attr({
                      'data-name' : 'John',
                      'data-category' : 'Student',
                      'data-semester' : 'sixth'
         });
});

This way you can set multiple attributes to an element.

Monday, November 9, 2015

Using Bootstrap with CodeIgniter

Bootstrap is  a widely used responsive html framework. It is based on grid layout and is easier to understand and easier to implement. Bootstrap is an awesome framework to use in web projects. You can read more here twitter bootstrap.
Download the latest version of Bootstrap and extract it. There will be three folders namely css, fonts and js. css folder contains the minified and uncompressed .css files, fonts folder contains icon files and js folder contains the minified and uncompressed .js files.
Now create a folder called assets in the codeIgniter root folder in the server. It will be like: C:/Program files/wamp/www/codeIgniter/assets/. Copy the three folders css, js and fonts that we downloaded into the assets folder. If you are working in ubuntu, you might want to change permission of the newly created assets folder and its subfolders like this chmod 755 -R /var/www/codeIgniter/assets.
Now create a templates folder in application/views and create two files header.php and footer.php in it. The beauty of this setup is we can include this header and footer in every page and in case any editing is required we need to edit in one file.
 Put these in the header.php
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bootstrap example</title>
  <link href="<?php echo base_url("assets/css/bootstrap.min.css"); ?>" rel="stylesheet">
  <link rel="stylesheet" href="<?php echo base_url("assets/css/font-awesome.min.css");?>">
 </head>
 <body>
  <div id="content">
Put these in the footer.php
  </div>
  <!-- Scripts -->
  <script src="<?php echo base_url("assets/js/jquery-1.10.2.min.js");?>"></script>
  <script src="<?php echo base_url("assets/js/bootstrap.min.js");?>"></script>
 </body>
</html>
It is important to use the function base_url() to output the location of files. It ensures cross-platform compatibility. Now create a folder called pages in application/views folder and create a file page_one.php and put the code in it. You can have your own bootstrap code in it.
page_one.php
    <div class="container-fluid text-center">
      <h1>Hello, world!</h1>
      <h3><p class="text-center">This was a simple tutorial to show how bootstrap framework can be used 
        alongside codeIgniter framework. hope you guys enjoyed it and learned something new! Cheers..</p>
      </h3>
      <p><a class="btn btn-primary btn-lg" role="button">Learn more &raquo;</a></p>
      <hr>
    </div>
    <div class="container">
      <!-- Example row of columns -->
      <div class="row">
        <div class="col-md-4">
          <h2>Heading</h2>
          <p>Article contents goes here. </p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
        <div class="col-md-4">
          <h2>Heading</h2>
          <p>Article contents goes here </p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
       </div>
        <div class="col-md-4">
          <h2>Heading</h2>
          <p>Article contents goes here</p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
      </div>

      <hr>

      <footer>
        <p>&copy; Company 2013</p>
      </footer>
    </div> <!-- /container -->
Now create and write the controller code in pages.php in application/controllers folder
pages.php
<?php
class Pages extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->helper('url_helper');
 }

        public function load($page)
        {
         $this->load->view('templates/header');
         $this->load->view('pages/'.$page);
         $this->load->view('templates/footer');
        }
}
Now if you point the browser to your webroot followed by index.php/load/page_one then you will see a simple, clean html page developed using bootstrap framework. In my case the address is localhost/codeIgniter/index.php/load/page_one.

Okay so this is how you can use bootstrap in codeIgniter. Happy bootstrapping.. :)

Sunday, November 1, 2015

JQuery Ajax FormData

AJAX is a web technology and stands for 'Asynchronous Javascript And XML'. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page( without full page reloads).
Suppose we have a form with some input fields and a php action file to process the data. Normally once we submit the form using the submit button, the php action file is loaded in the browser and then the remaining processes are done. With ajax, we can avoid the loading of the php action file in the browser once the form is submitted. What is going behind the scene is that ajax script will take the values of our form fields and pass it to the php action file and the whole thing is done in the background. JQuery, the popularly used javascript framework, has a built-in ajax function too which makes ajax calls even more easier.

Suppose we have a form:

<form id="myForm">

     Username:<input id="username" type="text" />

     Photo:<input id="photo" type="file" />

     <input id="enter" type="button" value="Enter" />

</form>
Use JQuery's FormData object to collect the values of our form fields using FormData's append() function. Then use JQuery.ajax() function to post the data to the action.php file.
<script>
function post_data_using_ajax() {
    var formData = new FormData();
    formData.append('username', $('#username').val());
    formData.append('photo', $('#photo')[0].files[0]);
    jQuery.ajax({
        type: "POST",
        url: "action.php", // Our action file
        processData: false, // tell jQuery not to process the data
        contentType: false, // tell jQuery not to set contentType
        data: formData,
        success: function(res) {
            alert("Inserted successfully");
        }
    });
}
</script>
Bind the function to 'Enter' button of the form inside a script element and place it inside body.
<script>
 $("#enter").click(post_data_using_ajax);
</script>
Now you can process the form variables in the normal way in action.php
<?php
 // Do the database connection code if necessary

 $username = $_POST['username'];
 $filename = $_FILES['photo']['name'];
 $photo_path = "uploads/";

 //Upload the photo to the server
 move_uploaded_file($_FILES['photo']['tmp_name'],$path . $filename);

 //Do whatever you want like insert the variables to a mysql table etc...
?>
So here is the final html file.
form.html
<!DOCTYPE html>
<html>
 <head>
  <title>Ajax Example</title>
  <meta charset="utf-8">
 </head>
 <body>
  <div class="container">
   <form id="myForm">
    Username:<input id="username" type="text" />
    Photo:<input id="photo" type="file" />
    <input id="enter" type="button" value="Enter" />
   </form>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script>
   function post_data_using_ajax() {
       var formData = new FormData();
       formData.append('username', $('#username').val());
       formData.append('photo', $('#photo')[0].files[0]);
       jQuery.ajax({
           type: "POST",
           url: "action.php", // Our action file
           processData: false, // tell jQuery not to process the data
           contentType: false, // tell jQuery not to set contentType
           data: formData,
           success: function(res) {
               alert("Inserted successfully");
           }
       });
   }
  </script>
  <script>
   $("#enter").click(post_data_using_ajax);
  </script>
 </body>
</html>