Wednesday, November 26, 2014

How To Handle Errors in Codeigniter?

CodeIgniter lets you build error reporting into your applications using the functions such as..
show_error('message' [, int $status_code= 500 ] )
This function will display the error message supplied to it using the following error template: application/errors/error_general.php

show_404('page' [, 'log_error'])
This function will display the 404 error message supplied to it using the following error template: application/errors/error_404.php

log_message('level', 'message')
This function lets you write messages to your log files. You can three level options:  error, debug and info.
By default, on a clean install, CI will display ALL php errors of all severity. So if you make a mistake in your PHP coding, you'll see the errors in your browser..


CI uses PHP's error_reporting() function to define the level of error reporting, and you can find this in the main index.php file in the root of your CI install. It’s the first function you see.


Instead of E_ALL, you can change it to any of the predefined error constant that PHP understands to suit your needs. Obviously, once your site goes live, you should change from E_ALL to E_ERROR to show only messages for fatal run time problems. This will hide all php errors except those that will halt your script execution.

How to hide database error?
You can hide the database error by setting db_debug to FALSE in application/config/database.php.
It will display blank page if any database error will occur instead of displaying any kind of database table name or error on site.
  $db['default']['db_debug'] = FALSE; 
You can easily redirect to some other error page instead of showing blank page as follows.

$query = $this->db->get('your_table');  
if(!$query)
{
   show_error("This is where your error message will appear surrounded by this default template. ", 500 );
   exit;
}

When you call show_error(), you will generate page that looks like this. The layout can changed by modifying this file application/errors/error_general.php)


That's it. Feel free to comment.
Source: http://www.askaboutphp.com/172/codeigniter-handling-errors.html

Tuesday, November 25, 2014

How To Perform Multiple Tags Search Query using PHP, MYSQL & CodeIgniter?

I working on a tag based search. I have three tables tag(id,name), tagXmedia(id,tag_id,media_id), and media(id,...).
tagXmedia is the mapping table between the tag and media tables. This is a one to many relationship.
For instance I need to be able to search for an entry in the media table that is associated with both the "home" and "hawaii" tags.
SELECT media_id
FROM tagXmedia
WHERE tag_id IN (SELECT id FROM tag WHERE name IN ('home','hawaii'))
GROUP BY media_id
HAVING COUNT(tag_id) = 2;
If you wish to have it match more than just two tags, you can easily add them. Just remember to change the 2 in the HAVING clause.

Perform Multiple Tags Search using URL Parameters and Codeigniter
Within the query string, parameters (filters) are separated by ampersands (&), and multiple values per parameter are separated by commas. For example:
http://localhost/example/sheet?tags=value1,value2&param2=value

Here is the Codeigniter active-record query for performing multiple tags using comma separated values. Table structure are explained above.

  $this->db->select('tag.name, media.*');
  $this->db->join('tagXmedia', 'media.id = tagXmedia.media_id', 'left');
  $this->db->join('tags', 'tags.id = tagXmedia.tag_id', 'left');

  $tags = explode(',',$tags);
  $a_tag  = array_unique($tags);
  $tag_count = count($a_tag);
     
  $this->db->where_in('tag.name', $a_tag);     
  $count = "COUNT(tagXmedia.tag_id) = $tag_count ";
  $this->db->group_by('media.id');      
  $this->db->having($count);

  $query = $this->db->get('media');

Ref: http://stackoverflow.com/a/8762620

Thursday, November 20, 2014

Which IDE To Use When Coding in CodeIgniter?

People use various IDE to code in CodeIgniter (CI) depending on one's need. It is hard to tell which IDE is best to use to code in CI. I have been using Coda and Sublime text 2. It serve my purpose.
Some of the popular IDE which I have heard are
CodeLobster
Netbeans 7.0
zend studio
Eclipse
JetBrains PhpStorm
phpDesigner 8
Textmate
If you have any suggestion about other IDE's , do share.

Friday, November 14, 2014

How To Join Multiple Tables in Codeigniter?

By using CodeIgniter's Active Record class, you can just use the join method multiple times to join multiple tables.
$this->db->select('*');
$this->db->join('table2', 'table2.ID = table1.ID');
$this->db->join('table3', 'table3.ID = table1.ID');
$this->db->from('table1');
Permits you to write the JOIN portion of your query. If you need a specific type of JOIN you can specify it via the third parameter of the function. Options are: left, right, outer, inner, left outer, and right outer.
$this->db->join('table4', 'table4.ID = table1.ID', 'left');
// Produces: LEFT JOIN table4 ON table4.ID = table1.ID

Read more detail on https://ellislab.com/codeigniter/user-guide/database/active_record.html

Tuesday, October 28, 2014

How To Limit Characters in Div With jQuery?

It is really easy to limit the number of characters in a div, particular class, ID etc by a particular value.
$(function(){

  $(".target-div").each(function(i){

    var len = $(this).text().length;

    if(len > 100){

      $(this).text($(this).text().substr(0,100)+'...');

    }
  });
});
If desired, remove the dots from the end ('...'). I would recommend keeping it to let your users know that the text was shortened.

Monday, October 27, 2014

How To Upgrade Mysql/phpMyAdmin in MAMP?


Follow these simple steps to upgrade phpMyAdmin or Mysql in MAMP. The latest version was phpMyAdmin 4.2.10.1 (at the time of writing).
1. Download the latest version from http://www.phpmyadmin.net/home_page/index.php
2. Unpack the archive you just downloaded, the resulting folder should be called somewhat like "phpMyAdmin-x.y-all-languages"
3. Rename "/Applications/MAMP/bin/phpMyAdmin" to "/Applications/MAMP/bin/phpMyAdmin-OLD"
4. Copy "phpMyAdmin-x.y-all-languages" to "/Applications/MAMP/bin/"
5. Rename "/Applications/MAMP/bin/phpMyAdmin-x.y-all-languages" to "/Applications/MAMP/bin/phpMyAdmin"
6. Restart the MAMP and upgrading task is completed. You have successfully upgraded to latest phpMyAdmin or Mysql 4.2.10.1 version.

What is phpMyAdmin?
phpMyAdmin is a free software tool written in PHP, intended to handle the administration of MySQL over the Web. phpMyAdmin supports a wide range of operations on MySQL, MariaDB and Drizzle. Frequently used operations (managing databases, tables, columns, relations, indexes, users, permissions, etc) can be performed via the user interface, while you still have the ability to directly execute any SQL statement.

Wednesday, October 15, 2014

When And How To Use jQuery mouseenter And mouseleave Events?

If elements you are binding to are loaded with javascript after the document loads, it is better to use mouseenter and mouseleave events of jQuery.
$(document).on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
}, ".selector"); //pass the element as an argument to .on
This code will work for an element populated with JavaScript after a .load() event has happened. Just change your argument to the appropriate selector.

This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.

I have tried to use jQuery .on and hover for an above situation, but it didn't work.

Ref: http://stackoverflow.com/a/9827114

Friday, October 10, 2014

How To Capture Array Values from Dynamic input Fields Using PHP?

In my previous post, you were able to add multiple dynamic fields using jQuery. In this tutorial, we will collect values from those dynamically generated input fields, which can be displayed on user browser or store in MySql database.

Let's assume you have a HTML form with multiple input fields like example shown below. This fields are generated by jQuery code in my previous post.
<form method="post" action="collect_vals.php">
 <div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
  <div><input type="text" name="mytext[]"></div>
 </div>
</form>
Notice the name attribute mytext[] of each input fields? they all have same name. The brackets indicate that the value of such input field will be posted as an array, so another input field means another value to existing array.

Capture Array Values using PHP
Collecting values from above input fields is pretty simple, take a look at example below. Once the value is captured from input fields, you can output it on the browser.

We can directly access array values using array's indexed number, but this will cause error if indexed value doesn't exist in array.
echo $_POST["mytext"][0];
echo $_POST["mytext"][1];
Another way is using PHP implode, it converts POST array into string, separated by commas. Just make sure POST variable is not empty:
if($_POST){
    $subject = implode(",", $_POST["mytext"]);
    echo $text;
}
You can also loop through each POST array like so, result is same as above.
<?php
if(isset($_POST["mytext"])){
    
    $capture_field_vals ="";
    foreach($_POST["mytext"] as $key => $text_field){
        $capture_field_vals .= $text_field .", ";
    }
    
    echo $capture_field_vals;
}
?>

Save values into Database
You can save above captured strings on your database using MySql/MySqli.
<?php

//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO table ( captured_fields ) VALUES( $capture_field_vals )");

if($insert_row){
    print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}
?>


Source: Source: Capture Array Values from Dynamic input Fields using PHP

Thursday, October 9, 2014

How To Add or Duplicate Input Fields Dynamically Using jQuery?

If you are looking to add and remove duplicate input fields, here's another jQuery example below to do the task for you. This jQuery snippet adds duplicate input fields dynamically and stops when it reaches maximum allowed fields.


If you read comment lines carefully, the process is pretty straight forward. We start with 1 input field and let user add more fields until the count reaches maximum. Same process goes to delete button, when clicked, it removes current text field by removing the parent element, which is div element.
$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

HTML Code
Here's HTML code you need to place within BODY tag of your page, perhaps within a FORM tag.
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>
We start with single Input field and a “Add more Field” button to allow user to add more fields. The text input field is wrapped in div element, as explained above, on delete button click, it finds parent element, which is a div and removes it.

How to capture array values using PHP from these input fields and save it in mysql in my next post.

Source: Add/Remove Input Fields Dynamically with jQuery

Tuesday, October 7, 2014

How To Load JSON Data With jQuery, PHP and MySQL ?

This post shows how to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP script that gets the data from a MySQL database.

HTML Code
The initial HTML code looks like this:
<form>
    Fruit:
   <select name="name" id="fruitName">
      <option>Apple</option>
        <option>Banana</option>
        <option>Orange</option>
        <option>Pear</option>
    </select>
    Variety:
    <select name="variety" id="fruitVariety">
    </select>
</form>
The set of fruit names was already populated on the server-side and the default set of varieties could be too; I have chosen to populate them with Javascript in this example.

jQuery Code
The jQuery code needs to initially populate the variety drop down based on the value of the fruit drop down. It then needs to update the variety if the fruit drop down changes.

Assuming the PHP script to fetch the fruit is at /fruit-varieties.php do this:
function populateFruitVariety() {
   
    $.getJSON('/fruit-varities.php', {fruitName:$('#fruitName').val()}, function(data) {

        var select = $('#fruitVariety');
        var options = select.prop('options');
        $('option', select).remove();

        $.each(data, function(index, array) {
            options[options.length] = new Option(array['variety']);
        });

    });

}

$(document).ready(function() {
 
 populateFruitVariety();
 $('#fruitName').change(function() {
  populateFruitVariety();
 });
 
});
The "$.getJSON('/fruit-varities.php', {fruitName:$('#fruitName').val()}" line is what retrieves the data and it passes the currently selected fruit name value as part of the get string to the PHP script.

PHP Code
The PHP script connects to the database, retrieves the data for the selected fruit name and then returns it as a JSON encoded string.
$dsn = "mysql:host=localhost;dbname=[DATABASE NAME HERE]";
$username = "[USERNAME HERE]";
$password = "[PASSWORD HERE]";

$pdo = new PDO($dsn, $username, $password);

$rows = array();
if(isset($_GET['fruitName'])) {
    $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
    $stmt->execute(array($_GET['fruitName']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);

Downloadable example
A downloadable example can be found here. This contains a PHP file which connects to the database and returns data when the fruitName parameter is specified.
All you need to do is add in your database name, login name and password to the PHP file and create the fruit table. The SQL for doing this is included in a comment at the end of the PHP file.
The HTML file should then work as-is, as long as you run the whole thing through a web server (e.g. don't just open the HTML file in your web browser and expect it to work).

Source: Load JSON data with jQuery, PHP and MySQL

Tuesday, September 30, 2014

How To Show Select Box as Multiple, But Disable Multiple Selection?

I needed to display:
A html <select> box as a multiple enabled or vertically expanded box (not as dropdown list). So I set select box as multiple. Then it turn outs to be like this:
<select id="myName" multiple>
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

Problem
But how to disable multiple selection? (i.e. to allow only 1 selection)

Solution
Do not use the multiple attribute instead set the size for it. It will enable you to select just one option in the list. And it displays as multiple select or expanded box.
<select id="myName" size="3">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>
The size attribute specifies the number of visible options in a drop-down list. If the value of the size attribute is greater than 1, but lower than the total number of options in the list, the browser will add a scroll bar to indicate that there are more options to view.

Note: If you put multiple then user can select multiple items from the list.

source: http://stackoverflow.com/a/14155833

Thursday, September 25, 2014

How To Handle PHP Notice Error?

A notice means that while your code will work as expected, it isn't written "like it should be". It's like the compiler telling you "I know what you mean here and I can do it, but you shouldn't rely on this. Please write it differently so I don't have to make assumptions".
The following code generates a notice if $n is not set.
if($n==1)
{
   //do something
}
Therefore a notice by itself doesn't mean that something bad happens most of the time. However, fixing the notices is a pretty simple task.

A solution or suggestion would be something like this:
if (!empty($n) && $n == 1)
{
    //do something
}
empty checks for existence automatically (just like calling isset before it) but it also checks to make sure your value doesn't evaluate as false with values like false, 0, or '' (empty string).

Source: http://stackoverflow.com/a/5921010

Wednesday, September 24, 2014

How To Restrict Controllers Functions Based On User Roles in Codeigniter?

To restrict logged in users from an entire controller is fairly simple in Codeigniter.

   function __construct(){
 parent::__construct();

  // to protect the controller to be accessed only by registered users
   if(!$this->session->userdata('logged_in')){
                redirect('login', 'refresh');
           }
    }

This works great. The user is not allowed access to functions or methods within the controller unless they are authenticated or registered users.

If you want to restrict controllers functions/methods based on user roles, you can do the following way:

     function __construct(){
 parent::__construct();
     
 // to protect the controller to be accessed only by registered users
  if(!$this->session->userdata('logged_in')){
                redirect('login', 'refresh');
         }

         //list of protected methods to access (for example only by admin )
  $protected_methods = array('METHOD1', 'METHOD2', 'METHOD3');

          /*$this->session->userdata('logged_in') is the array containing user information such as name, email, user role etc.*/

          if($this->session->userdata('logged_in')['user_role'] == 'role1'){
                        
              //grab the controller/method name and compare with protected methods array
              if(in_array($this->router->method, $protected_methods)){      
          redirect('login', 'refresh');    
       }
               else {
               redirect('home', 'refresh');
              }
           }

      }

How it works:
You should simply do the check in the constructor of the class that you're calling.
Firstly, check if the user is authenticated or not. If user is not an authenticated, system redirect the user to Login page.
And use $this->router->method (it gives you the real controller/method names, even if you reroute them) to see what method the user is trying to access.
Check that against an array of methods that required some specific roles to access the methods/functions.
In this example, role1 is the user that is not allowed to access protected methods 1,2 and 3.
If the user has role i.e. role1, it will redirect to login page otherwise redirect to home page.

Thursday, August 28, 2014

Codeigniter form validation set_value and set_checkbox problem fixed

For example, I have two fields in my form first_name and last_name
I have set the validation rule only for first_name. 'set_value' should work for both the fields regardless of rule ? Right ?
- No, set_value or set_checkbox or set_select only works against the items you have chosen to validate using the form_validation class.

Solution
Simple way to fix this problem is to overwrite the core 'MY_form_helper.php' with some functions.
- Copy the following code and save it and name it as 'My_form_helper.php' and placed under 'application/helpers' folder. It will overwrite the core functions.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
/**
* Form Value
*
* Grabs a value from the POST array for the specified field so you can
* re-populate an input field or textarea.  If Form Validation
* is active it retrieves the info from the validation class
*
* @access   public
* @param   string
* @return   mixed
*/
if (!function_exists('set_value')) {
 
        function set_value($field = '', $default = '') {
                $OBJ = & _get_validation_object();
 
                if ($OBJ === TRUE && isset($OBJ->_field_data[$field])) {
                        return form_prep($OBJ->set_value($field, $default));
                } else {
                        if (!isset($_POST[$field])) {
                                return $default;
                        }
 
                        return form_prep($_POST[$field]);
                }
        }
 
}
 
if (!function_exists('set_checkbox')) {
 
        function set_checkbox($field = '', $value = '', $default = '') {
                $OBJ = & _get_validation_object();
 
                if ($OBJ === TRUE && isset($OBJ->_field_data[$field])) {
                        return form_prep($OBJ->set_checkbox($field, $value, $default));
                } else {
                        if (!isset($_POST[$field])) {
                                return '';
                        }
                        else{
                                if($_POST[$field] == $value)
                                {
                                        return 'checked=\'checked\'';
                                }
                        }
                }
        }
 
}
 
/* End of file MY_form_helper.php */
/* Location: ./application/helpers/MY_form_helper.php */ 
This will overwrite the core functions MY_form_helper.php and will work with all the fields regardless of validation rules.
Enjoy :)
Source: http://pastebin.com/h70F9esF

Tuesday, August 19, 2014

Simple Two Column CSS Responsive Layout

HTML STRUCTURE
Here is a simplified example of the HTML.
<div id="main">
<div class="wrap">
 
                <div id="primary">
                    <div id="content" role="main">
                        <p>Article content...</p>
                    </div>
                </div>
 
                <div id="secondary">
                    <div class="widget">
                        <p>Sidebar content...</p>
                    </div>
                </div>
 
            </div>
        </div>
CSS RESET
We'll use the CSS reset.
/* =Reset
-------------------------------------------------------------- */
 
* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin-top: 0;
}
 
html,
body,
div{
    margin: 0;
    padding: 0;
}

SINGLE COLUMN LAYOUT FOR MOBILE
We’ll start with just one column for the mobile layout, with the content column coming first and the sidebar below it. Before we get to that, lets add some color so we can tell the different elements apart.
/* =Color
-------------------------------------------------------------- */
 
#header{
    background: #cccccc;
}
 
#main{
    background: #dddddd;    
}
 
#secondary {
    border: 1px solid #bbbbbb;
}
The #header is gray and the #main section is lighter gray. Now let’s move on to the actual structure.
/* =Structure
-------------------------------------------------------------- */
 
.wrap{
    max-width: 1140px;
    margin: 0 auto;
    padding: 1em;
}
 
.wrap:after {
    content: "";
    display: table;
    clear: both;
}
 
#primary{
    max-width: 720px;
    margin: 0 auto;
}
 
#secondary{
    max-width: 400px;
    margin: 0 auto;
    padding: 1em;
}
Starting at the beginning, the .wrap divs have a maximum width of 1140px and are centered on larger devices by the setting the margin to “0 auto”. The padding is to keep the text from touching the borders of the browser on smaller screens.
The code in the .wrap:after section is to make sure each .wrap div contains all floated elements inside it, rather than letting the floated elements overlap the edges. This is often called a “clearfix” hack.
The #primary section sets a maximum width for the main content column. We don’t ever want a content column getting really wide because wide columns are more difficult to read. Here we’re limiting this column to 720px and centering it using “margin: 0 auto;” for when the screen is larger than 720px.
The #secondary section limits the sidebar width to 400px. Sidebar content is rarely intended to be displayed in a wide area. Since the sidebar will not be wider than 400px in the full two column layout, we limit it here also. This way the sidebar will appear in a consistent manner regardless of the screen size. Just like the other elements, we center it using “margin: 0 auto” and then give it a padding of 1em so the content doesn’t touch the border we gave it earlier.
Here’s what it should look like on mobile.

TWO COLUMN CSS LAYOUT
Here’s where we finally get to use CSS media queries. This is what it looks like:
/* =Media Queries
-------------------------------------------------------------- */
 
@media screen and (min-width : 900px) {
    #primary{
        float: left;
        width: 65%;
        padding-right: 1em;
    }
 
    #secondary{
        float: right;
        width: 35%;
    }
}
First let’s look at the @media screen line. This line determines when the enclosed CSS is applied. In this case, it is applied when the website is being displayed on a screen that has a width of 900px or more.
The #primary section is floated to the left and given a width of 65%. Then 1em of padding is added on the right to prevent the enclosed content from touching the sidebar that will be positioned next to the right of the main content.
The #secondary section is floated to the right and given a width of 35%, so that it sits next to the #primary section.
Here’s what it looks like on the desktop.

Finally, if we wanted the sidebar to be on the left and the content on the right, we would only need to change the float directions of the #primary and #secondary columns in the media query section of the stylesheet and change “padding-right” to “padding-left” on the #primary div.
/* =Media Queries
-------------------------------------------------------------- */
 
@media screen and (min-width : 900px) {
    #primary{
        float: right;
        width: 65%;
        padding-left: 1em;
    }
 
    #secondary{
        float: left;
        width: 35%;
    }
}
That’s all.If you have any questions or comments, feel free to let me know via the contact page. Thanks! Source: http://themefoundation.com/two-column-css-layout/

Thursday, June 26, 2014

How To Get All Attributes of an Element Using jQuery ?

You need to use attributes property that contains them all:

$(this).each(function() {
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
    if(this.specified) {
      console.log(this.name, this.value);
    }
  });
});
If you want to grab only the attributes that has prefix like data-* from image tags. Use data() property. data-* attributes are supported through .data() and will return all of the data- attribute inside an object as key-value pairs.
$('img').each(function() {
   var data = $(this).data();
    $.each(data, function(key, value) {    
      console.log(key, value);
   });
});

ref: http://stackoverflow.com/a/14645827
http://stackoverflow.com/a/4190650

Wednesday, June 25, 2014

How To Remove Specific Class And Attributes From Html Tags Using PHP?

I recommend PHP Simple HTML DOM Parser, let you manipulate HTML in a very easy way!. You can find tags on an HTML page with selectors just like jQuery.
$html = "<div>
<span class="test1 test2 test3" data-id="5"  >text 1</span><br />
<span class="test1 test3 test2">text 4</span></div>";
If just want to either empty or remove any class that has "test2" in it and remove attributes like "data-id". You can use PHP Simple HTML DOM Parser to remove specific class and attribute from HTML tags like below. In order to delete specific class from HTML tags, you can use SIMPlE PHP DOM Parser and preg_replace function. You can remove attributes easily using removeAttribute method.
// Find all elements with the class test2 attribute
foreach($html->find('[class=test2]') as $e){
    $e->removeAttribute("data-id"); //remove attribute 
    $e->class = preg_replace("/(?:^|\s)editable(?:\s|$)/msi", " ", $e->class);
}

echo $html;
The outcome
<div>
<span class="test1 test3">text 1</span><br />
<span class="test1 test3">text 4</span></div>

If you guys know any other efficient way, do share for our users. :)

Wednesday, June 18, 2014

How to Upload Files with CodeIgniter and AJAX?

Uploading files asynchronously with CodeIgniter can be confusing and frustrating experience. In this tutorial I will share the steps how I successfully implemented a file upload with CodeIgniter and ajax.

You need CodeIgniter, jQuery, and the script AjaxFileUpload which you can copy from bottom of this tutorial.

It's assumed you have a working knowledge of CodeIgniter and jQuery. But no prior knowledge of AjaxFileUpload is necessary. It is also assumed that you already have successfully set up CodeIgniter. For the sake of brevity and clarity, we are not going to use database to save file information.

Step 1. Creating a form
Create your view and name it upload.php. This view will contain our upload form.

<!doctype html>
<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
 <script src="<?php echo base_url()?>js/custom.js"></script>
 <script src="<?php echo base_url()?>js/ajaxfileupload.js"></script>
</head>
<body>
 <h1>Upload File</h1>
 <form method="post" action="" id="upload_file">
 <label for="userfile">File</label>
<input type="file" name="userfile" id="userfile" size="20" /> <input type="submit" name="submit" id="submit" /> </form> <h2>Files</h2> <div id="files"></div> </body> </html>
At the top; jQuery, AjaxFileUpload, and our own custom javascript files are loaded.
Then, we created a standard HTML form. The empty #files div is where the confirmation/failure message will be displayed.
Step 2. Custom Javascript
Create custom.js inside 'js' folder and Place the following code:
$(function() {
    $('#upload_file').submit(function(e) {
        e.preventDefault();
        $.ajaxFileUpload({
            url             :base_url + './upload/upload_file/', 
            secureuri       :false,
            fileElementId   :'userfile',
            dataType: 'JSON',
            success : function (data)
            {
               var obj = jQuery.parseJSON(data);                
                if(obj['status'] == 'success')
                {
                    $('#files').html(obj['msg']);
                 }
                else
                 {
                    $('#files').html('Some failure message');
                  }
            }
        });
        return false;
    });
});
The JavaScript hijacks the form submit and AjaxFileUpload takes over. In the background, it creates an iframe and submits the data via that.
We then check our return (which will be in JSON). Depending on the status(success/error), we display message.
Step 3. Uploading a File
The Controller
The URL we are uploading to is /upload/upload_file/, so create a new method in the upload controller, and place the following code in it.
public function upload_file()
{
  $status = "";
  $msg = "";
  $file_element_name = 'userfile';

 if ($status != "error")
{
  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'gif|jpg|png|doc|txt';
  $config['max_size'] = 1024 * 8;
  $config['encrypt_name'] = FALSE;

  $this->load->library('upload', $config);
  if (!$this->upload->do_upload($file_element_name))
  {
    $status = 'error';
    $msg = $this->upload->display_errors('', '');
  }
  else
   {
   $data = $this->upload->data();
   $image_path = $data['full_path'];
   if(file_exists($image_path))
   {
      $status = "success";
      $msg = "File successfully uploaded";
 }
 else
 {
  $status = "error";
  $msg = "Something went wrong when saving the file, please try again.";
 }
}
 @unlink($_FILES[$file_element_name]);
 }
 echo json_encode(array('status' => $status, 'msg' => $msg));
}

This code loads in the CodeIgniter upload library with a custom config. Remember to delete the temp file off the server, and echo out the JSON so we know what happened.

Files Folder
We should also create the folder our files will be uploaded to. Create new file in your web root called 'uploads', making sure it is writable by the server.

That's it, tutorial complete! If you run it, you should be able to upload a file, see it appear, all without leaving the page.

Note: I haven't added displaying, editing and deleting files.

Goodies:
Copy and paste the following javascript code and save as ajaxfileupload.js.

jQuery.extend({	

  createUploadIframe: function(id, uri)
	{
			//create frame
      var frameId = 'jUploadFrame' + id;
      var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
			if(window.ActiveXObject)
			{
        if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';

        }
        else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';

        }	
			}
			iframeHtml += ' />';
			jQuery(iframeHtml).appendTo(document.body);

      return jQuery('#' + frameId).get(0);			
  },
  createUploadForm: function(id, fileElementId, data)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		if(data)
		{
			for(var i in data)
			{
				jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
			}			
		}		
		var oldElement = jQuery('#' + fileElementId);
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id', fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);
		
		//set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');		
		return form;
  },

  ajaxFileUpload: function(s) {
    // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
    s = jQuery.extend({}, jQuery.ajaxSettings, s);
    var id = new Date().getTime()    
		var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
    // Watch for a new set of requests
    if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}      
    var requestDone = false;
    // Create the request object
    var xml = {} 
    if ( s.global )
      jQuery.event.trigger("ajaxSend", [xml, s]);
    // Wait for a response to come back
    var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
      try
			{				
				if(io.contentWindow)
				{
 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
        	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

				}else if(io.contentDocument)
				{
 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
        	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}	
      }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
      if ( xml || isTimeout == "timeout")
			{				
        requestDone = true;
        var status;
        try {
          status = isTimeout != "timeout" ? "success" : "error";
          // Make sure that the request was successful or notmodified
          if ( status != "error" )
{
            // process the data (runs the xml through httpData regardless of callback)
            var data = jQuery.uploadHttpData( xml, s.dataType );  
            // If a local callback was specified, fire it and pass it the data
            if ( s.success )
              s.success( data, status );
 
            // Fire the global callback
            if( s.global )
              jQuery.event.trigger( "ajaxSuccess", [xml, s] );
          } else
            jQuery.handleError(s, xml, status);
        } catch(e)
				{
          status = "error";
          jQuery.handleError(s, xml, status, e);
        }

        // The request was completed
        if( s.global )
          jQuery.event.trigger( "ajaxComplete", [xml, s] );

        // Handle the global AJAX counter
        if ( s.global && ! --jQuery.active )
          jQuery.event.trigger( "ajaxStop" );

        // Process result
        if ( s.complete )
          s.complete(xml, status);

        jQuery(io).unbind()

        setTimeout(function()
				{	try
					{
						jQuery(io).remove();
						jQuery(form).remove();	
						
					} catch(e)
					{
						jQuery.handleError(s, xml, null, e);
					}				

				}, 100)

        xml = null

      }
    }
    // Timeout checker
    if ( s.timeout > 0 )
		{
      setTimeout(function(){
        // Check to see if the request is still happening
        if( !requestDone ) uploadCallback( "timeout" );
      }, s.timeout);
    }
    try
		{

			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
      if(form.encoding)
			{
				jQuery(form).attr('encoding', 'multipart/form-data');   			
      }
      else
			{	
				jQuery(form).attr('enctype', 'multipart/form-data');			
      }			
      jQuery(form).submit();

    } catch(e)
		{			
      jQuery.handleError(s, xml, null, e);
    }
		
		jQuery('#' + frameId).load(uploadCallback	);
    return {abort: function () {}};	

  },

  uploadHttpData: function( r, type ) {
    var data = !type;
    data = type == "xml" || data ? r.responseXML : r.responseText;
    // If the type is "script", eval it in global context
    if ( type == "script" )
      jQuery.globalEval( data );
    // Get the JavaScript object, if JSON is used.
    if ( type == "json" )
      eval( "data = " + data );
    // evaluate scripts within html
    if ( type == "html" )
      jQuery("<div>").html(data).evalScripts();

    return data;
  }
})


If you are looking for delete and display features, you can find in below tutorial.

Reference site: http://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684

Monday, June 16, 2014

How To Display Images From Folder Using Codeigniter?

If you need to display images from folder/directory in the CodeIgniter, then the Directory Helper is what you looking for. The Directory Helper file contains functions that assist in working with directories.
<?php 
$this->load->helper('directory'); //load directory helper
$dir = "uploads/images/"; // Your Path to folder
$map = directory_map($dir); /* This function reads the directory path specified in the first parameter and builds an array representation of it and all its contained files. */

foreach ($map as $k)
{?>
     <img src="<?php echo base_url($dir)."/".$k;?>" alt="">
   
<?php }
          
?> 

Result: You will get all the images from the folder.

Wednesday, June 4, 2014

How To Fix MIME Type Error Using Codeigniter sendmail?

If you are using Codeiginiter mail class function, you can get following type of MIME type error.
This is a multi-part message in MIME format.
Your email application may not support this format.
How to fix the MIME error:
Follow the following steps if you get MIME type sendmail error.
1. Open system/libraries/email.php
2. Edit
  var $newline = "\n";
  var $crlf = "\n";

  to

  var $newline = "\r\n";
  var $crlf = "\r\n";
Hope this solves your problem.
If you found any problem and solution, do share to other readers as well. :)

Tuesday, June 3, 2014

How To Hide or Remove Disqus Footer?

I wanted to remove the footer of Disqus commenting system plugin. Disqus works fine, but the footer is little iterating. It turns out to be easy to hide or remove the Disqus footer from webpage. Just add following piece of style in your CSS file and Disqus footer won't be visible.



Just add following piece of style in your CSS file and Disqus footer won't be visible.
#disqus_thread{
     position: relative;
}
#disqus_thread:after{
     content: "";
     display: block;
     height: 55px;
     width: 100%;
     position: absolute;
     bottom: 0px;
     background:white;
}
Ref: http://stackoverflow.com/a/22217487

Monday, May 19, 2014

How To Rename or Change Mysql Database Name?

You can easily change or rename your database name using mysql interface.

Steps
1. Goto http://www.example.com/phpMyAdmin
2. Select database which you want to rename.
3. Goto operation tab there you will find input field to rename database.
4. Rename the database and press 'Go' and its done.

How To Limit Foreach Loop in PHP?

You can limit the foreach loop to any repetition. I needed to limit the foreach loop to two repetition.
I have used array_slice method inside foreach loop as following:
foreach(array_slice($articles, 0, 2) as $row ):
It was so easy.
The array_slice() function returns selected parts of an array.
Syntax
array_slice(array,start,length,preserve)

Thursday, May 15, 2014

Phantomjs - Some Useful Tips

Code Context
There are mainly two contexts in PhantomJS program: first, the PhantomJS program itself; second, the webpage open in your headless browser, i.e., access to the DOM.

How can I execute JavaScript on the given webpage itself inside PhantomJS?
The solution is page.evaluate (where page is the variable representing the current page "open" in your headless browser). page.evaluate takes, as argument, a function to-be executed in the context of the webpage. It can return a result from the webpage back to your PhantomJS program. For example, that you'd like to grab the text of an element on the current page with ID "foo":
var foo = page.evaluate(function() {
    return $("#foo").text;
})
You could then use foo in your PhantomJS program, successfully extracting the value from the webpage. Note: return values are limited to simple objects, rather than, say, functions.

IncludeJs and InjectJs
You can use PhantomJS to inject/include JavaScript files (jQuery and other libraries) in the current webpage using two functions: page.injectJs and page.includeJs.

Difference between injectJs and includeJs
page.injectJs pauses execution until the script is loaded, while page.includeJs loads the script like any other. page.includeJs includes external script from the specified url (usually a remote location) on the page and executes the callback upon completion. Injects external script code from the specified file into the page (like includeJs, except that the file does not need to be accessible from the hosted page) and returns true if injection is successful, otherwise it returns false.. Note: both accept callbacks.
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
 /* jQuery is loaded, now manipulate the DOM */
    var foo = page.evaluate(function() {
        return $("#foo").text;
    });
    // do what you gotta do with 'foo'
    // ...
});
The above snippet will open up a web page, include the jQuery library into the page and evaluate the statement.
Console.logging from your web browser
Well, if you type console.log("Hello, World!") in your PhantomJS program, that will be printed to your terminal. If, however, your webpage tries to log the same message, it will pass by unnoticed! So if your webpage prints a bunch of traces to the console, you'll never see 'em.
Specifically, the following code does nothing because "Hello, World!" is printed in the context of the browser:
page.evaluate(function() {
    console.log("Hello, World!")
})
So, what if you want to log messages to your terminal from within your webpage? The trick is to use the page.onConsoleMessage event and echo any messages printed in the browser out to your terminal. Try this:
page.onConsoleMessage = function(msg){
    console.log(msg);
};

waitFor.js
PhantomJS beginners constantly ask how they can wait for something to appear on their webpage before acting. For example, maybe they want a banner to appear and then extract some text from it. Say "#foo" is now a div that loads a few seconds after the page has appeared. If you simply use the following code, you'll get unexpected results, as the banner may not be loaded at the time of query:
var page = require('webpage').create();
page.open('http://www.sample.com', function() {
    var foo = page.evaluate(function() {
        return $("#foo").text;
    });
    // ...
    phantom.exit();
});
Instead, you should use waitFor.js, a nice JavaScript snippet provided by the PhantomJS guys. This function is pretty simple, but very, very useful. Essentially, it queries the page every few seconds (the exact interval is an optional parameter), executing a user-specified function when a certain condition has been met. Expanding on the previous example, our code might look like the following (excluding the lengthy definition of waitFor):

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 250); //< repeat check every 250ms
};


var page = require('webpage').create();
page.open('http://www.sample.com', function() {
    waitFor(function() {
            // Check in the page if a specific element is now visible
            return page.evaluate(function() {
                return $("#foo").is(":visible");
            });
        }, function() {
           var foo = page.evaluate(function() {
                return $("#foo").text;
            });
            // ...
            phantom.exit();
        });   
    });
});
Source: http://www.princeton.edu/~crmarsh/phantomjs/
https://github.com/ariya/phantomjs/wiki/API-Reference-WebPage

Thursday, April 24, 2014

How To Position a CSS Background Image x-pixels From The Right?

Background - Shorthand property
The shorthand property for background is simply "background":
body {background:url("image.png") no-repeat right top;}
To position a CSS background image x-pixel from right, you can use this shorthand
body {background:url("image.png") no-repeat right 10px top;}
Note: The above solution doesn't work for IE8 and lower.
The most appropriate answer is to use following shorthand, until all browsers supports it.
 body {background:url("image.png") no-repeat 97% top;}
When using the shorthand property the order of the property values is:
• background-color
• background-image
• background-repeat
• background-attachment
• background-position
It does not matter if one of the property values is missing, as long as the ones that are present are in this order.

Monday, March 31, 2014

How To Get Base URL With PHP?

You can easily get base URL with PHP with few steps. Following function can be useful when you need base URL for instance to show correct images, load stylesheets and scripts.
<?php
function home_base_url(){   

// first get http protocol if http or https

$base_url = (isset($_SERVER['HTTPS']) &&

$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';

// get default website root directory

$tmpURL = dirname(__FILE__);

// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",

//convert value to http url use string replace, 

// replace any backslashes to slash in this case use chr value "92"

$tmpURL = str_replace(chr(92),'/',$tmpURL);

// now replace any same string in $tmpURL value to null or ''

// and will return value like /localhost/my_website/ or just /my_website/

$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);

// delete any slash character in first and last of value

$tmpURL = ltrim($tmpURL,'/');

$tmpURL = rtrim($tmpURL, '/');


// check again if we find any slash string in value then we can assume its local machine

    if (strpos($tmpURL,'/')){

// explode that value and take only first value

       $tmpURL = explode('/',$tmpURL);

       $tmpURL = $tmpURL[0];

      }

// now last steps

// assign protocol in first value

   if ($tmpURL !== $_SERVER['HTTP_HOST'])

// if protocol its http then like this

      $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';

    else

// else if protocol is https

      $base_url .= $tmpURL.'/';

// give return value

return $base_url; 

}
?>

// and test it

echo home_base_url();

Output will be like this
local machine : http://localhost/my_website/ or https://myhost/my_website 

public : http://www.my_website.com/ or https://www.my_website.com/
use home_base_url function at index.php of your website and define it and then you can use this function to load script, css and content via url like
<?php
echo '<script src="'.home_base_url().'js/script.js" type="text/javascript"></script>'."\n";
?>
will create output like this :
<script src="http://www.my_website.com/js/script.js" type="text/javascript"?></script>
Source: http://stackoverflow.com/a/21723209

Tuesday, March 25, 2014

Smooth Scrolling to Anchor with jQuery


The days of abruptly jumping to an anchor link within a page are over. There exists different solutions to scroll smoothly.

What Smooth Scrolling to Anchor means ?
You click on a link, and the page smoothly and gracefully scrolls down to a specific section of content. This transition is easy on the eyes, it’s appealing, and damnit – it’s just plain cool!

We’ll utilize jQuery’s built-in function scrollTop() to do our heavy lifting.
This example works if your HTML is set up like so:
// content goes here

<a name="top" />
<a href="#bottom">Link</a>

// more content

<a href="#top">Link</a>
<a name="bottom" />

// more content


jQuery
$(function() {
 
  // scroll handler
  var scrollToAnchor = function( id ) {
 
    // grab the element to scroll to based on the name
    var elem = $("a[name='"+ id +"']");
 
    // if that didn't work, look for an element with our ID
    if ( typeof( elem.offset() ) === "undefined" ) {
      elem = $("#"+id);
    }
 
    // if the destination element exists
    if ( typeof( elem.offset() ) !== "undefined" ) {
 
      // do the scroll
      $('html, body').animate({
        scrollTop: elem.offset().top
      }, 1000 );
 
    }
    
  };
 
  // bind to click event
  $("a").click(function( event ) {
   
    // only do this if it's an anchor link
    if ( $(this).attr("href").match(/^#/) ) {
      
      // prevent default propagation
      event.preventDefault();
      
      // scroll to the location
      var href = $(this).attr('href').replace('#', '');
      scrollToAnchor( href );
 
      // if we have pushState
      if ( history.pushState ) {
        history.pushState( null, null, '#'+href );
      }
      
      // fallback to prevent jitter
      return false;
 
    }
 
  });
 
});


Just updated this again and added pushState in, so that it keeps track of the hash change in modern browsers. If a user clicks away after clicking your anchor link, it’ll take them back to the anchor position they were at instead of making them rescroll to that position.
Alternative 2
HTML
 <a href="#target" class="scrollMe">Go to </a>
 <div id="target">Lorem Ipsum...</div>
Jquery
$('a[href*=#]:not([href=#])').click(function() {
     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

       var target = $(this.hash);
       target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
         $('html,body').animate({
           scrollTop: target.offset().top - 20
         }, 1000);
         return false;
       }
     }
   });
Source: https://gist.github.com/jpederson/9496381
http://bradsknutson.com/blog/smooth-scrolling-to-anchor-with-jquery/

Friday, March 14, 2014

How to Show/Hide Read More link With jQuery?

Sometimes you have long text and few space to show it, with jQuery and CSS is very simple to hide part of the text and create a "Read more" link.
So, this is the HTML, please note that the value of links DIV ID is replicated as CLASS in the links and in the extra text:

<div class="section">
<div id="lorem">
Lorem ipsum dolor sit amet
<a class="read lorem" href="http://www.blogger.com/blogger.g?blogID=2335294175322090003#">(Read more...)</a>
 <a class="read hide lorem" href="http://www.blogger.com/blogger.g?blogID=2335294175322090003#">(Hide...)</a>
 </div>

<div class="more lorem">
Praesent commodo, tellus vehicula facilisis laoreet,enim tellus sagittis metus, vel posuere risus tellus vel quam. Praesent fermentum, risus nec sagittis volutpat
 </div>

</div>
<div class="section">
<div id="nullam">
Nullam fringilla hendrerit nisi et varius.
<a class="read nullam" href="http://www.blogger.com/blogger.g?blogID=2335294175322090003#">(Read more...)</a>
 <a class="read hide nullam" href="http://www.blogger.com/blogger.g?blogID=2335294175322090003#">(Hide...)</a>
 </div>

<div class="more nullam">
Mauris blandit ullamcorper purus, sit amet imperdiet tortor suscipit et. Nulla luctus magna eu dolor tempor pharetra. Sed egestas, massa id consectetur
 </div>

</div>

With CSS we hide one of the links and the extra text.
<style type="text/css">
.more, .hide{ display:none;}
</style>
Then the jQuery!
$(".read").click(function (){
    var i=$(this).parent().attr("id"); //We get the ID in the parent DIV 
    $("a."+i).toggle();  //switch the link with toggle()
    $("div."+i).slideToggle("slow");
  });

Source: You can view the demo @ http://nelsondev.blogspot.se/2012/11/a-read-morehide-link-with-jquery.html

Thursday, March 6, 2014

How To Send Email To Multiple Recipients With Attachments Using Codeigniter ?

Sending email is very simple in Codeigniter. The following piece of code will email with attachments to all recipients at once. It will prevent showing all recipients address in email, and will email it separately for each recipient.
//loading necessary helper classes
$this->load->library('email');
$this->load->helper('path');
$this->load->helper('directory'); 

//setting path to attach files 
$path = set_realpath('assets/your_folder/');
$file_names = directory_map($path);

foreach ($list as $name => $address)
{
    //if you set the parameter to TRUE any attachments will be cleared as well  
    $this->email->clear(TRUE);
    $this->email->to($address);
    $this->email->from('your@example.com');
    $this->email->subject('Here is your info '.$name);
    $this->email->message('Hi '.$name.' Here is the info you requested.'); 
    
    foreach($file_names as $file_name)
    {
     
      $this->email->attach($path.$file_name);
    
    }

    $this->email->send();
}


Here $list contains array of Recipient name and email ID. Make sure to use clear(TRUE) at the beginning of each iteration.
Example used above is taken from http://ellislab.com/codeigniter/user-guide/libraries/email.html.

Tuesday, March 4, 2014

How To Send Email With An Attachment In Codeigniter?

You need to use following two CodeIgniter's robust classes.
1. Email Library : CodeIgniter's robust Email Class library to make sending email very simple and easy.
2. Path Helper : The Path Helper file contains functions that permits you to work with file paths on the server.

Here is a basic example demonstrating how you might send email with attachment. Note: This example assumes you are sending the email from one of your controllers.
$this->load->library('email');
$this->load->helper('path');

$this->email->from('your@example.com', 'Your Name');
$this->email->to('someone@example.com'); 
$this->email->cc('another@another-example.com'); 
$this->email->bcc('them@their-example.com'); 

$this->email->subject('Email Test');
$this->email->message('Testing the email class.'); 

/* This function will return a server path without symbolic links or relative directory structures. */
$path = set_realpath('uploads/pdf/');
$this->email->attach($path . 'yourfile.pdf');  /* Enables you to send an attachment */


$this->email->send();

echo $this->email->print_debugger();


The above email sending example is used in CodeIgniter User Guide Version 2.1.4.

Firefox And IE Custom Select Dropwdown Problem Solved

This will make a custom dropdown works across all the browsers. So putting it all together the following should be sufficient.

/* IE FIX! */
select::-ms-expand {
    display: none;
}
  
/* Firefox FIX! */
select {
    outline : none;
    overflow : hidden;   
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;  
     text-indent : 0.01px;/* this is important! */
    text-overflow: ''; /* this is important! */  
}

Wednesday, February 26, 2014

How To Add Multiple DISQUS Threads On Same Page Using Codeigniter ?

Recently, I came around a problem with the Disqus comment system while I needed multiple disqus comment threads on one page. I have solved my problem using following method.

You can add multiple or several disqus threads on same page using little trick. You can read about reset method in Using Disqus on AJAX sites

Let's start with the control set for loading the Disqus module in a form of a "show comments" link below each individual post that would point to some function outside and pass all the necessary attributes for loading Disqus for the first time or resetting it with new parameters if it was already loaded.

We need disqus_identifier that tells Disqus how to uniquely identify the current page and disqus_url that tells Disqus the location of the page for permalinking purposes.

<div class="wrapper-1">
<a onclick="loadDisqus(jQuery(this), 'upcoming', '<?php echo base_url()."#!upcomingEvents"; ?>');">
Show comments</a>
</div>

<div class="wrapper-2">
<a onclick="loadDisqus(jQuery(this), 'future', '<?php echo base_url()."#!futureTrends"; ?>');">
Show comments</a>
</div>

Armed with the controls, let's create a generic outside function that seals the deal. Put that in a file somewhere, in the page header or anywhere you like.
<script type="text/javascript">
var disqus_shortname = 'your-sites-short-name-in-disqus';
var disqus_identifier;
var disqus_url;

function loadDisqus(source, identifier, url) {

if (window.DISQUS) {
   jQuery('#disqus_thread').insertAfter(source);
   /** if Disqus exists, call it's reset method with new parameters **/

    DISQUS.reset({
  reload: true,
  config: function () { 
   this.page.identifier = identifier.toString();    //important to convert it to string
   this.page.url = url;
  }
 });
} else {
//insert a wrapper in HTML after the relevant "show comments" link

   jQuery('<div id="disqus_thread"></div>').insertAfter(source);
   disqus_identifier = identifier; //set the identifier argument
   disqus_url = url; //set the permalink argument
   //append the Disqus embed script to HTML
   var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
   dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
   jQuery('head').append(dsq);
}
};
</script>
While using DISQUS.reset method, you must follow following requirements
Both variables this.page.identifier and this.page.URL
Full hashbang #!

Source: http://mystrd.at/articles/multiple-disqus-threads-on-one-page/
http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites

Wednesday, February 19, 2014

How To Use Callback Function In Ignited Datatables ?

I did some research on jQuery datatables wrapper [IgnitedDatatables] and made it working on a project to load huge data. One problem where i stuck was how to use callback function on edit columns. After several hours of try, i fixed it. Below is the solution on how i fixed it.

This post is not about how to use Ignited Datatables. I assume that you have working Ignited Datatables .

This example is taken from https://github.com/n1crack/IgnitedDatatables-php-library/blob/master/examples/callback_functions/ajax.php
$this->datatables->select('customer_id, first_name, last_name, email')
->from('customer')
->add_column('edit', 'Edit', 'customer_id')
->add_column('delete', 'Delete', 'customer_id')
->edit_column('email', '$1', strtolower('email')) // php functions
->edit_column('email', '$1', $this->custom_email('email'))  // custom functions
->edit_column('first_name', '$1', $this->fix_first_name('first_name'));

echo $this->datatables->generate();
// Callback Functions
function custom_email($val)
{
  return substr($val, 0, 3) . '..' . strstr($val, "@");
}


function fix_first_name($val)
{
  return ucwords(strtolower($val));
}

How to use callback function properly in an ignited datatables is shown below.

The above solution (custom edit_column callback function ) will not work for example, if you want to check the status of the user and want to display active or inactive status instead of 1 or 0.

I just want to tell you that you have to put callback functions in the Codeigniter helper file and not in the same controller. A CodeIgniter helper file is a PHP file with multiple functions. It is not a class.
To make it work. you have to load the helper file ($this->load->helper('My_datatable_helper')) before $this->datatables->generate() method.

Do remember that callbacks are made inside a library file which of course has no direct access to which controller uses it. Therefore, it is much easier or actually, just possible (from a library point of view) to use helpers instead for their callbacks.
/* Controller */

$this->load->helper('My_datatable_helper');  //load before generate function
->edit_column('status', '$1', 'check_status($status)')  // custom callback functions
echo $this->datatables->generate();
The controller has check_status($status) callback function to display ACTIVE OR INACTIVE depending on status (0 or 1 in the mysql database). In order to achieve that, you need to create a Codeigniter helper file and save this to 'application/helpers/' directory. I created 'MY_datatable_helper.php' and place a function inside. The check_status function checks the status variable and return Active, it is 1 otherwise Inactive. Below is the helper file:
/* MY_datatable_helper.php*/

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/** 
*  edit_column callback function in Codeigniter (Ignited Datatables)
*
* Grabs a value from the edit_column field for the specified field so you can
* return the desired value.  
*
* @access   public
* @return   mixed
*/

if ( ! function_exists('check_status'))
{
    function check_status($status = '')
    {
        return ($status == 1) ? 'Active' : 'Inactive';
    }   
}

/* End of file MY_datatable_helper.php */
/* Location: ./application/helpers/MY_datatable_helper.php */  

All credit goes to codeigniter Ignited-Datatables library. You can download the library from https://github.com/IgnitedDatatables/Ignited-Datatables

Monday, February 17, 2014

How To Get All Files Of Directory-Subdirectories as Dropdown List Using Codeigniter?

I have a folders inside a view directory. Some of the folders contains files and some other contains another subfolder with its file. What I want is list list all the files of folders and subfolders inside a view directory.

I found a the Directory Helper in Codeigniter. It contains functions that assist in working with directories. I used following function (recursive method) to create a drop-down list with files inside a view directory.
<?php
$this->load->helper('directory'); //load directory helper
$dir = APPPATH. "views/your_folder/";
$map = directory_map($dir);
echo "<select name='yourfiles'>";

function show_dir_files($in,$path) { foreach ($in as $k => $v) { if (!is_array($v)) {?> <option><?php echo $path,$v ?></option> <?php } else { print_dir($v,$path.$k.DIRECTORY_SEPARATOR); } } } show_dir_files($map,''); // call the function echo "</select>"; ?>

Friday, February 14, 2014

How To Dynamically Set Select Option Selected Using Jquery?

I have a select field with some options in it and want to select a specific option of a select tag dynamically:
The select List as follows:
<select id="my_val">
      <option value="1">Red</option>
      <option value="2">Green</option>
      <option value="3">Blue</option>
</select>

You can solve the above problem using following small piece of jquery function.
 $(document).on('change', '#my_val', function(e) { 
 
     e.preventDefault();
     var option_val = $("#my_val").val(); //store the dynamic value of select option
      $( "#my_val" ).find( 'option[value="' + option_val + '"]' ).prop( "selected", true ); //Set select option 'Selected'
                                   
});
There may be many other possible solutions. Above one worked best for me.

Wednesday, January 29, 2014

Assigning Multiple Classes For Click Event Using jQuery

I have an click event that I want to assign to more than one class. The reason for this is that I'm using this event on different places in my application, and the buttons you click have different styling in the different places.

I have used following method and it worked for me. You can select multiple classes at once with jQuery like this:
$(".class1, .class2").click(function(){
   alert("clicked");    
});​
Fiddle: http://jsfiddle.net/Afg5s/1/

In this way you can assign more than one class for any event using jQuery.

Source: http://stackoverflow.com/a/10511922

Tuesday, January 28, 2014

How to Add Multiple Languages Support in CodeIgniter ?

CodeIgniter comes with multi-language support, also known as internationalization which enables us to dynamically present our application’s interface in different languages without duplicating the existing source code for each language.

Configuring Multi-Language Support
First we need to configure the necessary files before we can start using language support. The CodeIgniter config file, located in the application/config directory, contains an option called language which defines the default language of the application.
<?php
$config['language'] = 'english';

CodeIgniter allows you to drop in as many languages as you want in the ../application/language/ folder. For example, if I wanted to add support for Swedish, I would create a folder inside language called "swedish". All language files must end in _lang. Let’s create some language files that contain error messages for a sample application. Create the file english/message_lang.php (it’s important that all of the language files have the suffix _lang.php). The following code contains some sample entries for the content of our language file.

Also keep in mind that for every key must be present in all of your language files. So if your ../language/english/message_lang.php file looks like this:
<?php
$lang["msg_first_name"] = "First Name";
$lang["msg_last_name"] = "Last Name";
$lang["msg_dob"] = "Date of Birth";
$lang["msg_address"] = "Address";
// more keys...
Then your ../language/swedish/message_lang.php file must look something like this:
<?php
$lang["msg_first_name"] = "Förnamn";
$lang["msg_last_name"] = "Efternamn";
$lang["msg_dob"] = "Födelsedatum";
$lang["msg_address"] = "adress";
// more keys...
Note that order does not matter in the language files. All keys are part of a larger array.

Of course, you can have multiple language files inside a single language directory. It’s recommended to group your messages into different files based on their context and purpose, and prefix your message keys with a file-specific keyword for consistency.

Loading the Language Files
There are two ways to load a language files in Codeigniter. Applying hook is the best alternative to add multi languages support.
1. Only Controller
2. Using Hook

1. Only Controller
Even though we create language files, they are not effective until we load them inside controllers. The following code shows how we can load the files inside a controller:
<?php
class TestLanguage extends CI_Controller
{
    public function __construct() {
        parent::__construct();       
        $this->lang->load("message","english");
        // or ($this->lang->load("message","swedish");)
    }
 
    function index() {
        $data["language_msg"] = $this->lang->line("msg_first_name");
        $this->load->view('language_view', $data);
    }
}

Here we’ve used a controller’s constructor to load the language file so it can be used throughout the whole class, then we reference it in the class’ index() method.

The first parameter to the lang->load() method will be the language’s filename without the _lang suffix. The second parameter, which is optional, is the language directory. It will point to default language in your config if it’s not provided here.

We can directly reference the entries of a language file using the lang->line() method and assign it’s return to the data passed into the view templates. Inside the view, we can then use the above language message as $language_msg.

<?php
$this->lang->line("language_msg");
There may be an occasion when we need to load language files directly from the views as well. For example, using language items for form labels might be considered a good reason for directly loading and accessing messages inside views. It’s possible to use the same access method for these files inside views as inside controllers.
<?php
lang("language_msg");
2. Using Hooks
Luckily, we can use CodeIgniter hooks to build a quick and effective solution for loading language files automatically for each controller. CodeIgniter calls a few built-in hooks as part of its execution process. We’ll use the post_controller_constructor hook which is called immediately after our controller is instantiated and prior to any other method calls.

We enable hooks in our application by setting the enable_hooks parameter in the main config file.
<?php
$config['enable_hooks'] = TRUE;
Then we can open the hooks.php file inside the config directory and create a custom hook as shown in the following code:
<?php
$hook['post_controller_constructor'] = array(
    'class' => 'LanguageLoader',
    'function' => 'initialize',
    'filename' => 'LanguageLoader.php',
    'filepath' => 'hooks'
);
This defines the hook and provides the necessary information to execute it. The actual implementation will be created in a custom class inside the application/hooks directory. This hooks class will load the language dynamically from the session.
<?php
class LanguageLoader
{
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');
 
        $site_lang = $ci->session->userdata('site_lang');

/* If you want to use cookie instead of session 
$site_lang = $ci->input->cookie('site_lang'); */

        if ($site_lang) {
            $ci->lang->load('message',$ci->session->userdata('site_lang'));
        } else {
            $ci->lang->load('message','english');
        }
    }
}

Inside the LanguageLoader class we get the active language and load the necessary language files, or we load the default language if the session key is absent. We can load multiple language files of a single language inside this class.

Switching Between Different Languages
Once we have established support for multiple languages, a link for each language can be provided to the user, generally in one of our application’s menus, which the users can click and switch the language. A session or cookie value can be used to keep track of the active language.

Let’s see how we can manage language switching using the hooks class we generated earlier. First we need to create a class to switch the language; we’ll be using a separate controller for this as shown below:
<?php
class LangSwitch extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }
 
    function switchLanguage($language = "") {
        $language = ($language != "") ? $language : "english";
        $this->session->set_userdata('site_lang', $language);
        redirect(base_url());
    }
}
Then we need to define links to switch each of the available languages.
<a href='<?php echo $base_url; ?>langswitch/switchLanguage/english'>English</a>
<a href='<?php echo $base_url; ?>langswitch/switchLanguage/swedish'>Swedish</a>
Whenever the user chooses a specific language, the switchLanguage() method of the LangSwitch class will assign the selected languages to the session and redirect the user to the home page. Now the active language will be changed in the session and will load the specific language file for the active language.

Source: http://www.sitepoint.com/multi-language-support-in-codeigniter/

Friday, January 24, 2014

Swedish Language Form Validation Support For CodeIgniter 2.1.x

I have translated the form validation into Swedish Language of CodeIgniter Version 2.1.X. This will be useful when you are adding multi-languages support in Codeigniter 2.1.x. This will help you to show form validation rules in Swedish Language.

Just add following form_validation_lang.php under application/language/swedish folder.
<?php

$lang['required']   = "%s är obligatoriskt.";
$lang['isset']    = "%s måste innehålla ett värde.";
$lang['valid_email']          = "%s måste innehålla en giltig e-post.";
$lang['valid_emails']          = "%s måste innehålla all giltig e-poster.";
$lang['valid_url']   = "%s måste innehålla en giltig URL.";
$lang['valid_ip']   = "%s måste innehålla en giltig IP.";
$lang['min_length']   = "%s måste innehålla minst %s tecken.";
$lang['max_length']   = "%s får inte vara längre än %s tecken.";
$lang['exact_length']          = "%s måste vara exakt %s tecken.";
$lang['alpha']    = "%s får bara innehålla bokstäver.";
$lang['alpha_numeric']          = "%s får bara innehålla alfanumeriska tecken.";
$lang['alpha_dash']          = "%s får bara innehålla alfanumeriska tecken, understreck och bindestreck.";
$lang['numeric']   = "%s måste innehålla ett nummer.";
$lang['is_numeric']   = "%s får bara innehålla numeric tecken.";
$lang['integer']   = "%s måste innehålla ett integer.";
$lang['regex_match']          = "%s är inte i rätt format.";
$lang['matches']   = "%s skiljer sig från %s.";
$lang['is_unique']    = "%s måste innehålla ett unikt värde.";
$lang['is_natural']   = "%s får bara innehålla positiva nummer.";
$lang['is_natural_no_zero']         = "%s måste innehålla ett nummer större än noll.";
$lang['decimal']   = "%s måste innehålla ett decimal nummer.";
$lang['less_than']   = "%s måste innehålla ett nummer mindre än %s.";
$lang['greater_than']          = "%s måste innehålla ett nummer större än %s.";


/* End of file form_validation_lang.php */
/* Location: ./application/language/swedish/form_validation_lang.php */

Thursday, January 23, 2014

How To Upload Multiple files Using CodeIgniter ?

This is just an extension to the existing Codeigniter's Upload class to take advantage of multiple uploads in one form field.

Installation Copy MY_Upload.php to your application/libraries directory. If you are using a prefix other than MY_ for your classes and/or alternative file paths, adjust accordingly.

Usage Load the Upload class as usual, in your controller call the function do_multi_upload(). If you are uploading a single file, it'll default to the regular do_upload() method. In the form, set field names to array (e.g. name="userfile[]")

MY_Upload.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Exenstion File Uploading Class
 */
  
class MY_Upload extends CI_Upload {
 
 public function do_multi_upload( $field = 'userfile', $return_info = TRUE, $filenames = NULL ){

  // Is $_FILES[$field] set? If not, no reason to continue.
  if ( ! isset($_FILES[$field]))
  {   
   $this->set_error('upload_no_file_selected');
   return FALSE;   
  }
  
  //If not every file filled was used, clear the empties
  
  foreach( $_FILES[$field]['name'] as $k => $n )
  { 
   if( empty( $n ) )
   {
   
    foreach( $_FILES[$field] as $kk => $f )
    {    
     unset( $_FILES[$field][$kk][$k] );     
    }        
   }   
  }
  
  // Is the upload path valid?
  if ( ! $this->validate_upload_path($field) )
  {

   // errors will already be set by validate_upload_path() so just return FALSE
   return FALSE;
  }

  //Multiple file upload
  if( is_array( $_FILES[$field] ) )
  { 
   //$count = count($_FILES[$field]['name']); //Number of files to process
   
   foreach( $_FILES[$field]['name'] as $k => $file )
   {    
    // Was the file able to be uploaded? If not, determine the reason why.
    if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$k] ) )
    {     
     $error = ( ! isset($_FILES[$field]['error'][$k])) ? 4 : $_FILES[$field]['error'][$k];
     
     switch($error)
     {
      case 1: // UPLOAD_ERR_INI_SIZE
       $this->set_error('upload_file_exceeds_limit');
       break;
      case 2: // UPLOAD_ERR_FORM_SIZE
       $this->set_error('upload_file_exceeds_form_limit');
       break;
      case 3: // UPLOAD_ERR_PARTIAL
       $this->set_error('upload_file_partial');
       break;
      case 4: // UPLOAD_ERR_NO_FILE
       $this->set_error('upload_no_file_selected');
       break;
      case 6: // UPLOAD_ERR_NO_TMP_DIR
       $this->set_error('upload_no_temp_directory');
       break;
      case 7: // UPLOAD_ERR_CANT_WRITE
       $this->set_error('upload_unable_to_write_file');
       break;
      case 8: // UPLOAD_ERR_EXTENSION
       $this->set_error('upload_stopped_by_extension');
       break;
      default :   $this->set_error('upload_no_file_selected');
       break;
     }
  
     return FALSE;
    }
        
    // Set the uploaded data as class variables
    $this->file_temp = $_FILES[$field]['tmp_name'][$k];
    $this->file_size = $_FILES[$field]['size'][$k];
    $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$k]);
    $this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
    
    if(empty($filenames))
    {
     $this->file_name = $this->_prep_filename($_FILES[$field]['name'][$k]);     
    }
    else
    {
     $this->file_name = $this->_prep_filename($filenames[$k]);
    }
    
    $this->file_ext  = $this->get_extension($this->file_name);
    $this->client_name = $this->file_name;
    
    // Is the file type allowed to be uploaded?
    if ( ! $this->is_allowed_filetype())
    {
     $this->set_error('upload_invalid_filetype');
     return FALSE;
    }
    
    // if we're overriding, let's now make sure the new name and type is allowed
    if ($this->_file_name_override != '')
    {
     $this->file_name = $this->_prep_filename($this->_file_name_override);
  
     // If no extension was provided in the file_name config item, use the uploaded one
     if (strpos($this->_file_name_override, '.') === FALSE)
     {
      $this->file_name .= $this->file_ext;
     }
  
     // An extension was provided, lets have it!
     else
     {
      $this->file_ext  = $this->get_extension($this->_file_name_override);
     }
  
     if ( ! $this->is_allowed_filetype(TRUE))
     {
      $this->set_error('upload_invalid_filetype');
      return FALSE;
     }
    }
 
    // Convert the file size to kilobytes
    if ($this->file_size > 0)
    {
     $this->file_size = round($this->file_size/1024, 2);
    }
  
    // Is the file size within the allowed maximum?
    if ( ! $this->is_allowed_filesize())
    {
     $this->set_error('upload_invalid_filesize');
     return FALSE;
    }
  
    // Are the image dimensions within the allowed size?
    // Note: This can fail if the server has an open_basdir restriction.
    if ( ! $this->is_allowed_dimensions())
    {
     $this->set_error('upload_invalid_dimensions');
     return FALSE;
    }
 
    // Sanitize the file name for security
    $this->file_name = $this->clean_file_name($this->file_name);
  
    // Truncate the file name if it's too long
    if ($this->max_filename > 0)
    {
     $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
    }
  
    // Remove white spaces in the name
    if ($this->remove_spaces == TRUE)
    {
     $this->file_name = preg_replace("/\s+/", "_", $this->file_name);
    }
  
    /*
     * Validate the file name
     * This function appends an number onto the end of
     * the file if one with the same name already exists.
     * If it returns false there was a problem.
     */
    $this->orig_name = $this->file_name;
  
    if ($this->overwrite == FALSE)
    {
     $this->file_name = $this->set_filename($this->upload_path, $this->file_name);
  
     if ($this->file_name === FALSE)
     {
      return FALSE;
     }
    }
  
    /*
     * Run the file through the XSS hacking filter
     * This helps prevent malicious code from being
     * embedded within a file.  Scripts can easily
     * be disguised as images or other file types.
     */
    if ($this->xss_clean)
    {
     if ($this->do_xss_clean() === FALSE)
     {
      $this->set_error('upload_unable_to_write_file');
      return FALSE;
     }
    }
  
    /*
     * Move the file to the final destination
     * To deal with different server configurations
     * we'll attempt to use copy() first.  If that fails
     * we'll use move_uploaded_file().  One of the two should
     * reliably work in most environments
     */
    if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
    {
     if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
     {
      $this->set_error('upload_destination_error');
      return FALSE;
     }
    }
  
    /*
     * Set the finalized image dimensions
     * This sets the image width/height (assuming the
     * file was an image).  We use this information
     * in the "data" function.
     */
    $this->set_image_properties($this->upload_path.$this->file_name);
  
    
    if( $return_info === TRUE )
    {     
     $return_value[$k] = $this->data();    
    }
    else
    {    
     $return_value = TRUE;    
    }    
   }
   
   return $return_value;  
  }
  else //Single file upload, rely on native CI upload class
  {  
   $upload = self::do_upload();   
   return $upload;  
  } 
 }

}

?>
Source: https://github.com/nicdev/CodeIgniter-Multiple-File-Upload