article

Sunday, May 11, 2014

How to Select / Deselect All Checkboxes using jQuery

How to Select / Deselect All Checkboxes using jQuery
//index.html
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('#selecctall').click(function(event) {  //on click
        if(this.checked) { // check select status
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox1"              
            });
        }else{
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox1"                      
            });        
        }
    });
   
});
</script>
<style>
ul.chk-container li {
    border-bottom: 1px solid #E7E7E7;
    padding: 3px;list-style:none;
}
</style>
<ul class="chk-container">
<li><input type="checkbox" id="selecctall"/> Selecct All</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item1"> This is Item 1</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item2"> This is Item 2</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item3"> This is Item 3</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item4"> This is Item 4</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item5"> This is Item 5</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item6"> This is Item 6</li>
<li><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Do not select this</li>
</ul>

jquery custom selectbox

jquery custom selectbox
//index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html>
 <head>
  <style type='text/css'>
   div.selectBox
   {
    position:relative;
    display:inline-block;
    cursor:default;
    text-align:left;
    line-height:30px;
    clear:both;
    color:#888;
   }
   span.selected
   {
    width:167px;
    text-indent:20px;
    border:1px solid #ccc;
    border-right:none;
    border-top-left-radius:5px;
    border-bottom-left-radius:5px;
    background:#f6f6f6;
    overflow:hidden;
   }
   span.selectArrow
   {
    width:30px;
    border:1px solid #60abf8;
    border-top-right-radius:5px;
    border-bottom-right-radius:5px;
    text-align:center;
    font-size:20px;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
    background:#4096ee;
   }
   
   span.selectArrow,span.selected
   {
    position:relative;
    float:left;
    height:30px;
    z-index:1;
   }
   
   div.selectOptions
   {
    position:absolute;
    top:28px;
    left:0;
    width:198px;
    border:1px solid #ccc;
    border-bottom-right-radius:5px;
    border-bottom-left-radius:5px;
    overflow:hidden;
    background:#f6f6f6;
    padding-top:2px;
    display:none;
   }
    
   span.selectOption
   {
    display:block;
    width:80%;
    line-height:20px;
    padding:5px 10%;
   }
   
   span.selectOption:hover
   {
    color:#f6f6f6;
    background:#4096ee; 
   }   
  </style>
  <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
 </head>
 <body>
 <script type='text/javascript'><!--
   $(document).ready(function() {
    enableSelectBoxes();
   });
   
   function enableSelectBoxes(){
    $('div.selectBox').each(function(){
     $(this).children('span.selected').html($(this).children('div.selectOptions').children('span.selectOption:first').html());
     $(this).attr('value',$(this).children('div.selectOptions').children('span.selectOption:first').attr('value'));
     
     $(this).children('span.selected,span.selectArrow').click(function(){
      if($(this).parent().children('div.selectOptions').css('display') == 'none'){
       $(this).parent().children('div.selectOptions').css('display','block');
      }
      else
      {
       $(this).parent().children('div.selectOptions').css('display','none');
      }
     });
     
     $(this).find('span.selectOption').click(function(){
      $(this).parent().css('display','none');
      $(this).closest('div.selectBox').attr('value',$(this).attr('value'));
      $(this).parent().siblings('span.selected').html($(this).html());
     });
    });    
   }//-->
  </script>
  <div class='selectBox'>
   <span class='selected'></span>
   <span class='selectArrow'>▼</span>
   <div class="selectOptions" >
    <span class="selectOption" value="Option 1">Option 1</span>
    <span class="selectOption" value="Option 2">Option 2</span>
    <span class="selectOption" value="Option 3">Option 3</span>
   </div>
  </div>
 </body>
</html>

Ajax Contact Form with an Attachment (jQuery & PHP)

Ajax Contact Form with an Attachment (jQuery and  PHP)
//index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Ajax Contact Form</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#submit_btn").click(function() { 
        //get input field values
  
        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_phone      = $('input[name=phone]').val();
  var attach_file     = $('input[name=file_attach]')[0].files[0];
        var user_message    = $('textarea[name=message]').val();
        
        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        if(user_phone=="") {    
            $('input[name=phone]').css('border-color','red'); 
            proceed = false;
        }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
   $(".loading-img").show(); //show loading image
   $(".submit_btn").hide(); //hide submit button
   
   //data to be sent to server   
   var post_data = new FormData();    
   post_data.append( 'userName', user_name );
   post_data.append( 'userEmail', user_email );
   post_data.append( 'userPhone', user_phone );
   post_data.append( 'userMessage',user_message);
   post_data.append( 'file_attach', attach_file );
   
   //instead of $.post() we are using $.ajax()
   //that's because $.ajax() has more options and can be used more flexibly.
   $.ajax({
     url: 'contact_me.php',
     data: post_data,
     processData: false,
     contentType: false,
     type: 'POST',
     dataType:'json',
     success: function(data){
     //load json data from server and output message     
     if(data.type == 'error')
     {
      output = '<div class="error">'+data.text+'</div>';
     }else{
      output = '<div class="success">'+data.text+'</div>';
      
      //reset values in all input fields
      $('#contact_form input').val(''); 
      $('#contact_form textarea').val(''); 
     }
     
     $("#result").hide().html(output).slideDown(); //show results from server
     $(".loading-img").hide(); //hide loading image
     $(".submit_btn").show(); //show submit button
     }
   });

        }
    });
    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<fieldset id="contact_form">
<legend>Contact Form</legend>
    <div id="result"></div>
    <label for="name"><span>Name</span>
    <input type="text" name="name" id="name" placeholder="Enter Your Name" />
    </label>
    
    <label for="email"><span>Email Address</span>
    <input type="email" name="email" id="email" placeholder="Enter Your Email" />
    </label>
    
    <label for="phone"><span>Phone</span>
    <input type="text" name="phone" id="phone" placeholder="Phone Number" />
    </label>
    
    <label for="phone"><span>Attachment</span>
    <input type="file" name="file_attach" id="file_attach" />
    </label>
    
    <label for="message"><span>Message</span>
    <textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
    </label>
    
    <label><span> </span>
    <button class="submit_btn" id="submit_btn">Submit</button>
    <img src="ajax-loader.gif" class="loading-img" style="display:none">
    </label>
</fieldset>
</body>
</html>
//style.css
#contact_form{
 width:350px;
 padding:20px;
 border: 1px solid #DDD;
 border-radius: 5px;
 font-family: Arial, Helvetica, sans-serif;
 font-size: 11px;
 font-weight: bold;
 color: #666666;
 background:#FAFAFA;
 margin-right: auto;
 margin-left: auto;
}
#contact_form legend{
 font-size: 15px;
 color: #C9C9C9;
}
#contact_form label{
 display: block;
 margin-bottom:5px;
}
#contact_form label span{
 float:left;
 width:100px;
 color:#666666;
}
#contact_form input{
 height: 25px;
 border: 1px solid #DBDBDB;
 border-radius: 3px;
 padding-left: 4px;
 color: #666;
 width: 230px;
 font-family: Arial, Helvetica, sans-serif;
}
#contact_form textarea{
 border: 1px solid #DBDBDB;
 border-radius: 3px;
 padding-left: 4px;
 color: #666;
 height:100px;
 width: 230px;
 font-family: Arial, Helvetica, sans-serif;
}
.submit_btn {
 border: 1px solid #D8D8D8;
 padding: 5px 15px 5px 15px;
 color: #8D8D8D;
 text-shadow: 1px 1px 1px #FFF;
 border-radius: 3px;
 background: #F8F8F8;
}
.submit_btn:hover 
{
 background: #ECECEC;
}
.success{
 background: #CFFFF5;
 padding: 10px;
 margin-bottom: 10px;
 border: 1px solid #B9ECCE;
 border-radius: 5px;
 font-weight: normal;
}
.error{
 background: #FFDFDF;
 padding: 10px;
 margin-bottom: 10px;
 border: 1px solid #FFCACA;
 border-radius: 5px;
 font-weight: normal;
}
//contact_me.php
<?php
if($_POST)
{
 $to_Email    = "recipient_email@yourdomain.com"; //Replace with recipient email address
 $subject        = 'contact form'; //Subject line for emails
 
 //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
 
  //exit script outputting json data
  $output = json_encode(
  array(
   'type'=>'error', 
   'text' => 'Request must come from Ajax'
  ));
  
  die($output);
    } 
 
 //check $_POST vars are set, exit if any missing
 if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
  die($output);
 }

 //Sanitize input data using PHP filter_var().
 $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
 $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
 $user_Phone       = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
 $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
 
 //additional php validation
 if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
  die($output);
 }
 if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
  die($output);
 }
 if(!is_numeric($user_Phone)) //check entered data is numbers
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Only numbers allowed in phone field'));
  die($output);
 }
 if(strlen($user_Message)<5) //check emtpy message
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
  die($output);
 }
 
 ### Attachment Preparation ###
 $file_attached = false; //initially file is not attached
 
 if(isset($_FILES['file_attach'])) //check uploaded file
 {
  //get file details we need
  $file_tmp_name    = $_FILES['file_attach']['tmp_name'];
  $file_name     = $_FILES['file_attach']['name'];
  $file_size     = $_FILES['file_attach']['size'];
  $file_type     = $_FILES['file_attach']['type'];
  $file_error    = $_FILES['file_attach']['error'];
  
  //exit script and output error if we encounter any
  if($file_error>0)
  {
   $mymsg = array( 
   1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
   2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
   3=>"The uploaded file was only partially uploaded", 
   4=>"No file was uploaded", 
   6=>"Missing a temporary folder" ); 
   
   $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
   die($output); 
  }
 
  //read from the uploaded file & base64_encode content for the mail
  $handle = fopen($file_tmp_name, "r");
  $content = fread($handle, $file_size);
  fclose($handle);
  $encoded_content = chunk_split(base64_encode($content));
  
  //now we know we have the file for attachment, set $file_attached to true
  $file_attached = true;
 }

 if($file_attached) //continue if we have the file
 {
  # Mail headers should work with most clients (including thunderbird)
  $headers = "MIME-Version: 1.0\r\n";
  $headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
  $headers .= "From:".$user_Email."\r\n";
  $headers .= "Subject:".$subject."\r\n";
  $headers .= "Reply-To: ".$user_Email."" . "\r\n";
  $headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";
 
  $headers .= "--".md5('boundary1')."\r\n";
  $headers .= "Content-Type: multipart/alternative;  boundary=".md5('boundary2')."\r\n\r\n";
  
  $headers .= "--".md5('boundary2')."\r\n";
  $headers .= "Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n";
  $headers .= $user_Message."\r\n\r\n";
 
  $headers .= "--".md5('boundary2')."--\r\n";
  $headers .= "--".md5('boundary1')."\r\n";
  $headers .= "Content-Type:  ".$file_type."; ";
  $headers .= "name=\"".$file_name."\"\r\n";
  $headers .= "Content-Transfer-Encoding:base64\r\n";
  $headers .= "Content-Disposition:attachment; ";
  $headers .= "filename=\"".$file_name."\"\r\n";
  $headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
  $headers .= $encoded_content."\r\n";
  $headers .= "--".md5('boundary1')."--"; 
 }else{
  # Mail headers for plain text mail
  $headers = 'From: '.$user_Email.'' . "\r\n" .
  'Reply-To: '.$user_Email.'' . "\r\n" .
  'X-Mailer: PHP/' . phpversion();
 }
 
 //send the mail
 $sentMail = @mail($to_Email, $subject, $user_Message, $headers);
 
 if(!$sentMail) //output success or failure messages
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
  die($output);
 }else{
  $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email'));
  die($output);
 }
}
?>

Thursday, May 1, 2014

PHPMailer in CodeIgniter

PHPMailer in CodeIgniter 

The first thing we do download PHPMailer library then move it to /system/application/libraries or /application/libraries/

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

class My_PHPMailer {
    public function My_PHPMailer() {
        require_once('PHPMailer/class.phpmailer.php');
    }
}
The controller
<?php
class My_Controller extends Controller {
    public function My_Controller(){
        parent::Controller();
        $this->load->library('My_PHPMailer');
    }
    public function send_mail() {
        $mail = new PHPMailer();
        $mail->IsSMTP(); // we are going to use SMTP
        $mail->SMTPAuth   = true; // enabled SMTP authentication
        $mail->SMTPSecure = "ssl";  // prefix for secure protocol to connect to the server
        $mail->Host       = "smtp.gmail.com";      // setting GMail as our SMTP server
        $mail->Port       = 465;                   // SMTP port to connect to GMail
        $mail->Username   = "myusername@gmail.com";  // user email address
        $mail->Password   = "password";            // password in GMail
        $mail->SetFrom('info@yourdomain.com', 'Firstname Lastname');  //Who is sending the email
        $mail->AddReplyTo("response@yourdomain.com","Firstname Lastname");  //email address that receives the response
        $mail->Subject    = "Email subject";
        $mail->Body      = "HTML message
";
        $mail->AltBody    = "Plain text message";
        $destino = "addressee@example.com"; // Who is addressed the email to
        $mail->AddAddress($destino, "Ednalan");

        $mail->AddAttachment("images/phpmailer.gif");      // some attached files
        $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want
        if(!$mail->Send()) {
            $data["message"] = "Error: " . $mail->ErrorInfo;
        } else {
            $data["message"] = "Message sent correctly!";
        }
        $this->load->view('sent_mail',$data);
    }
}

SWFUpload in CodeIgniter

SWFUpload in CodeIgniter

What is SWFUpload?
SWFUpload is a library that allows to our website’s users to upload files to the server, using a combination of Flash and JavaScript.

Download library


The form
application/views
<?php echo form_open('process_form/process'); 
// Here we put the controller's URL and the function which will process the form?>
<div>
<?php
echo form_label('File:','file');
$data = array(  'id' => 'txtFileName',
'value' => '',
'size' => 50,
'disabled' => 'disabled',
'style' => 'border: solid 1px; background-color: #FFFFFF;');
echo form_input($data); //Insert the text field which will hold the file anem once it is uploaded
?>
<span id="spanButtonPlaceholder"></span>
(20 MB max)
</div>
<div id="fsUploadProgress"></div>
<input type="hidden" name="hidFileID" id="hidFileID" value="" />
<br />
<?php
$extra = 'id="btnSubmit"';
echo form_submit('upload','Send',$extra);
echo form_close();
?>
<!-- Add JavaScript files for SWFUpload -->
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/swfupload.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/handlers.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/fileprogress.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend settings
upload_url: "<?php echo base_url();?>process_form/upload",
file_post_name: "resume_file",
// Flash file settings
file_size_limit : "20 MB", //File size limit
file_types : "*.jpg", // or you could use something like: "*.doc;*.wpd;*.pdf",
file_types_description : "Image Files",
file_upload_limit : 0,
file_queue_limit : 1,
// Event handler settings
swfupload_loaded_handler : swfUploadLoaded,file_dialog_start_handler: fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
//upload_start_handler : uploadStart, // I could do some client/JavaScript validation here, but I don't need to.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
// Button Settings
button_image_url : "<?php echo base_url();?>img/upload_flash_button_61x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22,
// Flash Settings
flash_url : "<?php echo base_url();?>swf/swfupload/swfupload.swf",
flash9_url : "<?php echo base_url();?>swf/swfupload/swfupload_fp9.swf",
custom_settings : {
progress_target : "fsUploadProgress",
upload_successful : false
},
// Debug settings
debug: false
});
};
</script>
The controller
<?php
class process_form extends Controller {
public function process()
{
...
//Here we take the file's name
$file_name = $this->input->post('hidFileID');
//Once we have the file's name, we could insert into the database
//or whatever is needed
...
}

public function upload()
{
$config['upload_path'] = "path/to/the/folder/for/the/file/";
 $config['allowed_types'] = 'jpg';
 $size_mb = 20; //Max file size allowed in MB
 $config['max_size'] = $size_mb * 1024; //

 $this->load->library('upload');
 $this->upload->initialize($config);
 if (!$this->upload->do_upload('resume_file'))
 {
     $this->data["params"]["error"] = array('error_upload' => $this->upload->display_errors());
     echo $this->upload->display_errors();
 }
 else
 {
     $uploaded_file = $this->upload->data();

     //Return to the form the final name of the file once it was uploaded
     echo $uploaded_file["file_name"];
 }
}
}

Wednesday, April 30, 2014

Get URL and URL Parts in JavaScript

Get URL and URL Parts in JavaScript
 
JavaScript can access the current URL

http://tutorial101.blogspot.com/example/currenturl

window.location.protocol = "http"
window.location.host = "tutorial101.blogspot.com"
window.location.pathname = "example/currenturl"

full URL path in JavaScript:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

breath up the pathname, for example a URL like http://tutorial101.blogspot.com/example/currenturl, you can split the string on "/" characters
<script>
 var pathArray = window.location.pathname.split( '/' );
 var secondLevelLocation = pathArray[2]; //access the different parts by the parts of the array
 alert(secondLevelLocation); //results = currenturl
 </script>

Monday, March 24, 2014

How To Implement Pagination In Codeigniter ion_auth library?

How To Implement Pagination In Codeigniter ion_auth library?

Controller

function display_user()
 {
  $this->data['title'] = "Display User";

  if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
  {
   redirect('auth', 'refresh');
  }

  $this->load->library('pagination');
  $config = array();
  $config["base_url"] = base_url() . "auth/display_user/";;
  $config['total_rows'] = $this->ion_auth->users()->num_rows();
  $config['per_page'] = '30';

  //pagination customization using bootstrap styles
  $config['full_tag_open'] = ' <ul class="pagination pull-right">';
  $config['full_tag_close'] = '</ul><!--pagination-->';
  $config['first_link'] = '« First';
  $config['first_tag_open'] = '<li class="prev page">';
  $config['first_tag_close'] = '</li>';

  $config['last_link'] = 'Last »';
  $config['last_tag_open'] = '<li class="next page">';
  $config['last_tag_close'] = '</li>';

  $config['next_link'] = 'Next →';
  $config['next_tag_open'] = '<li class="next page">';
  $config['next_tag_close'] = '</li>';

  $config['prev_link'] = '← Previous';
  $config['prev_tag_open'] = '<li class="prev page">';
  $config['prev_tag_close'] = '</li>';

  $config['cur_tag_open'] = '<li class="active"><a href="">';
  $config['cur_tag_close'] = '</a></li>';

  $config['num_tag_open'] = '<li class="page">';
  $config['num_tag_close'] = '</li>';


  $this->pagination->initialize($config);

  $the_uri_segment = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
  $config['uri_segment'] = $the_uri_segment;


  //list the users
  $this->data['users'] = $this->ion_auth->offset($this->uri->segment($the_uri_segment))->limit($config['per_page'])->users()->result();

  foreach ($this->data['users'] as $k => $user)
  {
   $this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
  }

  $this->data['links'] = $this->pagination->create_links();
  //set the flash data error message if there is one
  $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');


  $this->data['include'] = 'auth/display_user';
  $this->_render_page('auth/template', $this->data);

 }

View

<?php echo $links;?>

How To Dynamically Set Select Option Selected Using Jquery?

How To Dynamically Set Select Option Selected Using Jquery? 

 
<select id="my_val">
      <option value="1">Red</option>
      <option value="2">Green</option>
      <option value="3">Blue</option>
</select>

 $(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'                         
});

How To Send Email With An Attachment In Codeigniter?

How To Send Email With An Attachment In Codeigniter?
$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();

How To Send Email To Multiple Recipients With Attachments Using Codeigniter

How To Send Email To Multiple Recipients With Attachments Using Codeigniter 



 
//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();
}

Sunday, March 23, 2014

How To Integrate Codeigniter Form Validation Library and jQuery AJAX

How To Integrate Codeigniter Form Validation Library and jQuery AJAX Controller

 
/* controller/example.php*/
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Example extends CI_Controller{

function index()
 {
  $data['include'] = 'jquery_ci_form';
  $this->load->view('template', $data);  
 }
 function jquery_save()
 {
    
  $this->load->library('form_validation');
  $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
  $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
  $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
  
  if ($this->form_validation->run() == FALSE)
  {
      
   echo json_encode(array('st'=>0, 'msg' => validation_errors()));
  }
  else
  {
   
   $username = $this->input->post('username');
   $password = $this->input->post('password');
   $email = $this->input->post('email');
   
   //...save values to database 
   
   echo json_encode(array('st'=>0, 'msg' => 'Successfully Submiited'));
  }
  
 }
}

View
 
/* view/template.php */
<?php $this->load->view('includes/header'); ?>
<?php //$this->load->view('includes/sidebar'); ?>
<?php $this->load->view($include); ?>
<?php $this->load->view('includes/footer'); ?>
/* view/jquery_ci_form.php */
<?php echo form_open('example/jquery_save', array('id'=>'frm')); ?>
<div id="validation-error"></div>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>

jQuery
 
/* assets/js/custom.js*/
$(document).ready(function() {
$('#frm').submit(function(){
 $.post($('#frm').attr('action'), $('#frm').serialize(), function( data ) {
 if(data.st == 0)
  {
   $('#validation-error').html(data.msg);
  }
    
  if(data.st == 1)
  {
    $('#validation-error').html(data.msg);
  }
    
 }, 'json');
 return false;   
   });
});

Making AJAX request with JSON

Making AJAX request with JSON


 testjson.js
 
$.post("http://localhost/demo/controller/function", {'name1' : value1, 'name2' : value2}, //name1 is the name of the parameter that send, something similar to name1=val1&name2=val2
    function(data)
    {
        $.each(data.items, function(i,item){
            alert("value: "+item.value+" name: "+item.name); //item.value e item.name because in the data object the information is set in this way: [{value:name},{value:name}...]
        });
    }, "json"
 );

Controller
 
function funcion()
 {
   $data["my_data"] = $this->example_model->get_examples($this->input->post('name1'),$this->input->post('name2'));
   //$data["my_data"] will contain an array like Array("0" => Array("value" => value1, "name" => name1), "1" => Array("value" => value2, "name" => name2)...)
   $this->load->view('json/json_example_view',$data);
 }

View
 
<?php echo json_encode($datos); ?>

PHPMailer in CodeIgniter

PHPMailer in CodeIgniter

The first thing download the library
http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/

move folder /system/application/libraries

create a new PHP file in the CodeIgniter’s library directory called my_phpmailer.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class My_PHPMailer {
    public function My_PHPMailer() {
        require_once('PHPMailer/class.phpmailer.php');
    }
}
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Phpmailer extends CI_Controller {
 public function My_Controller(){
        parent::Controller();
        $this->load->library('My_PHPMailer');
  $this->load->library('session');
    }
  function index($msg = NULL)
 {
  $data['message'] = $msg;
  $this->load->view('contactus',$data);
 }
 public function send_mail() {
        $mail = new PHPMailer;
  //From email address and name
  $mail->From = "from@yourdomain.com";
  $mail->FromName = "Full Name";
  //To address and name
  $mail->addAddress("recepient1@example.com", "Recepient Name");
  $mail->addAddress("recepient1@example.com"); //Recipient name is optional
  //Address to which recipient will reply
  $mail->addReplyTo("reply@yourdomain.com", "Reply");
  //CC and BCC
  $mail->addCC("cc@example.com");
  $mail->addBCC("bcc@example.com");
  //Send HTML or Plain Text email
  $mail->isHTML(true);
  $mail->Subject = "Subject Text";
  $mail->Body = "<i>Mail body in HTML</i>";
  $mail->AltBody = "This is the plain text version of the email content"; 
   if(!$mail->send()) {
    $data["message"] = "Error: " . $mail->ErrorInfo;
  } else {
   $data["message"] = "<p><h3>Message sent correctly!</h3></p>";
  } 
        $this->load->view('contactus',$data);
    }
}
View
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Codeigniter 3.1.10 Dev - Phpmailer </title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Oleo+Script:400,700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Teko:400,700" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body id="page-top" class="index">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Oleo+Script:400,700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Teko:400,700" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<section id="contact">
   <div class="section-content">
    <h1 class="section-header">Get in <span class="content-header wow fadeIn " data-wow-delay="0.2s" data-wow-duration="2s"> Touch with us</span></h1>
    <h3>PHPMailer in CodeIgniter with bootstrap contact form</h3>
   </div>
   <div class="contact-section">
   <div class="container"><?php if(! is_null($message)) echo $message;?>  
    <form action="send_mail" method="post">
     <div class="col-md-6 form-line">
        <div class="form-group">
         <label for="exampleInputUsername">Your name</label>
          <input type="text" class="form-control" id="" placeholder=" Enter Name">
        </div>
        <div class="form-group">
          <label for="exampleInputEmail">Email Address</label>
          <input type="email" class="form-control" id="exampleInputEmail" placeholder=" Enter Email id">
        </div> 
        <div class="form-group">
          <label for="telephone">Mobile No.</label>
          <input type="tel" class="form-control" id="telephone" placeholder=" Enter 10-digit mobile no.">
        </div>
       </div>
       <div class="col-md-6">
        <div class="form-group">
         <label for ="description"> Message</label>
          <textarea  class="form-control" id="description" placeholder="Enter Your Message"></textarea>
        </div>
        <div>
         <button type="submit" class="btn btn-default submit"><i class="fa fa-paper-plane" aria-hidden="true"></i>  Send Message</button>
        </div>
     </div>
    </form>
   </div>
  </section>
<style>
/*Contact sectiom*/
.content-header{
  font-family: 'Oleo Script', cursive;
  color:#fcc500;
  font-size: 45px;
}
.section-content{
  text-align: center; 

}
#contact{
    font-family: 'Teko', sans-serif;
  padding-top: 60px;
  width: 100%;
  width: 100vw;
  height: 550px;
  background: #3a6186; /* fallback for old browsers */
  background: -webkit-linear-gradient(to left, #3a6186 , #89253e); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to left, #3a6186 , #89253e); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    color : #fff;    
}
.contact-section{
  padding-top: 40px;
}
.contact-section .col-md-6{
  width: 50%;
}
.form-line{
  border-right: 1px solid #B29999;
}
.form-group{
  margin-top: 10px;
}
label{
  font-size: 1.3em;
  line-height: 1em;
  font-weight: normal;
}
.form-control{
  font-size: 1.3em;
  color: #080808;
}
textarea.form-control {
    height: 135px;
   /* margin-top: px;*/
}
.submit{
  font-size: 1.1em;
  float: right;
  width: 150px;
  background-color: transparent;
  color: #fff;
}
</style>  
</body>
</html>

Saturday, March 22, 2014

SWFUpload in CodeIgniter

SWFUpload in CodeIgniter

First we need to integrate the library
https://code.google.com/p/swfupload/downloads/list

create a folder in the root directory of your CodeIgniter application /swf/swfupload/  

View Form
<?php echo form_open('process_form/process'); 
// Here we put the controller's URL and the function which will process the form?>
<div>
<?php
echo form_label('File:','file');
$data = array(  'id' => 'txtFileName',
'value' => '',
'size' => 50,
'disabled' => 'disabled',
'style' => 'border: solid 1px; background-color: #FFFFFF;');
echo form_input($data); //Insert the text field which will hold the file anem once it is uploaded
?>
<span id="spanButtonPlaceholder"></span>
(20 MB max)
</div>
<div id="fsUploadProgress"></div>
<input type="hidden" name="hidFileID" id="hidFileID" value="" />
<br />
<?php
$extra = 'id="btnSubmit"';
echo form_submit('upload','Send',$extra);
echo form_close();
?>
<!-- Add JavaScript files for SWFUpload -->
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/swfupload.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/handlers.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/fileprogress.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend settings
upload_url: "<?php echo base_url();?>process_form/upload",
file_post_name: "resume_file",
// Flash file settings
file_size_limit : "20 MB", //File size limit
file_types : "*.jpg", // or you could use something like: "*.doc;*.wpd;*.pdf",
file_types_description : "Image Files",
file_upload_limit : 0,
file_queue_limit : 1,
// Event handler settings
swfupload_loaded_handler : swfUploadLoaded,file_dialog_start_handler: fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
//upload_start_handler : uploadStart, // I could do some client/JavaScript validation here, but I don't need to.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
// Button Settings
button_image_url : "<?php echo base_url();?>img/upload_flash_button_61x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22,
// Flash Settings
flash_url : "<?php echo base_url();?>swf/swfupload/swfupload.swf",
flash9_url : "<?php echo base_url();?>swf/swfupload/swfupload_fp9.swf",
custom_settings : {
progress_target : "fsUploadProgress",
upload_successful : false
},
// Debug settings
debug: false
});
};
</script>

The controller
 
<?php
class process_form extends Controller {
public function process()
{
...
//Here we take the file's name
$file_name = $this->input->post('hidFileID');
//Once we have the file's name, we could insert into the database
//or whatever is needed
...
}

public function upload()
{
$config['upload_path'] = "path/to/the/folder/for/the/file/";
 $config['allowed_types'] = 'jpg';
 $size_mb = 20; //Max file size allowed in MB
 $config['max_size'] = $size_mb * 1024; //

 $this->load->library('upload');
 $this->upload->initialize($config);
 if (!$this->upload->do_upload('resume_file'))
 {
     $this->data["params"]["error"] = array('error_upload' => $this->upload->display_errors());
     echo $this->upload->display_errors();
 }
 else
 {
     $uploaded_file = $this->upload->data();

     //Return to the form the final name of the file once it was uploaded
     echo $uploaded_file["file_name"];
 }
}
}

Upload file in yiiframework

Upload file in yiiframework


Create table t_users
 id_user varchar(30)
profile_picture varchar(100)
name varchar(50)

Form
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'tuser-form',
 'enableAjaxValidation'=>false,
 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>
<p class="note">
 Fields with <span class="required">*</span> are required.
</p>
 
<?php echo $form->errorSummary($model); ?>
 <div class="row">
  <?php echo $form->labelEx($model,'profile_picture'); ?>
  <?php echo $form->fileField($model,'profile_picture',array('size'=>60,'maxlength'=>200)); ?>
  <?php echo $form->error($model,'title'); ?>
 </div>
 
Controller 
$model->attributes=$_POST['TUser'];
 $model->profile_picture=CUploadedFile::getInstance($model, 'profile_picture');
 if($model->save()){
  if(strlen($model->profile_picture)>0)
   $model->profile_picture->saveAs(Yii::app()->basePath.'/../upload/'.$model->profile_picture);
  $this->redirect(array('view','id'=>$model->id_user));
 }
 
 filter files use the rules in your model
 public function rules()
    {
        return array(
            array('picture_profile', 'file', 'types'=>'jpg, gif, png'),
           ...
        );
    }

Make dropdownlist in yii framework

Make dropdownlist in yii framework

Create table tbl_country

 country_name  | id
 Philippines       | 1
 USA               | 2

<div class="row">
 <?php echo $form->dropDownList($model,'country_id',
  CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
  array('empty'=>'Select Country'))?>
</div>

Make checkbox using ajax load in yiiframework

Make checkbox using ajax load in yiiframework


 
<?php echo CHtml::checkBox("load_ajax",false,array('id'=>'load_risk_all'));echo "Load All Risk Child";
$url=CController::createUrl('project/vieweach',array('project_id'=>$model->project_id));
Yii::app()->clientScript->registerScript("check",
           '$("#load_risk_all").change(function(){
             if($(this).is(":checked")){
              $("#load_risk").load("'.$url.'");
              $("#load_risk").fadeIn();
             }else{
              $("#load_risk").html("");
             }
             })
          ',
           CClientScript::POS_READY);
 
?>
<div id="load_risk">
</div>

load() function in jQuery for loading the ajax content using $.ajax functions
$this->renderPartial('/risk/view_each',array('provider'=>$provider),false,true);

onChange event in checkbox htmlOption for supporting your own javascript model 
<?php echo CHtml::checkbox("load risk",false,array("onChange"=>"js:yourcustomfunction()")); ?> 

Using CMaskField in your yii framework

Using CMaskField in your yii framework


 
<?php
$this->widget('CMaskedTextField', array(
'model' => $model,
'attribute' => 'aluguel',
'mask' => '(999) 999-9999? x99999',
'htmlOptions' => array('size' => 6)
));
?>

<?php
$this->widget('CMaskedTextField', array(
'model' => $model,
'attribute' => 'aluguel',
'mask' => '9.999,99',
'charMap' => array('.'=>'[\.]' , ','=>'[,]'),
'htmlOptions' => array('size' => 6)));
?>

How to make CGridview with dropdown filter

How to make CGridview with dropdown filter


 
$this-<widget('zii.widgets.grid.CGridView',array(
   'dataProvider'=<$model-<search(),
   'id'=<'risk-id',
   'filter'=<$model,
   'columns'=<array(
   array(
      'name'=<'No',
      'type'=<'raw',
      'value'=<'$this-<grid-<dataProvider-<pagination-<currentPage*$this-<grid-<dataProvider-<pagination-<pageSize + $row+1',//this for the auto page number of cgridview
      'filter'=<''//without filtering 
   ),
   array(
      'name'=<'name',
      'type'=<'raw',
      'value'=<'Chtml::link(Chtml::encode($data["name"]),array("risk/view","id"=<$data["risk_id"]))',
      'filter'=<CHtml::listData(Risk::model()-<findAll(
                  array(
                   'select'=<array('name'),
                   'distinct'=<true
                    
                  )),"name","name")//this is the focus of your code
       
   ),
   array(
      'name'=<'date_identified',
      'type'=<'raw',
      'value'=<'Chtml::encode($data-<date_identified)'
   ),
   array(
      'name'=<'description',
      'type'=<'raw',
      'value'=<'Chtml::encode($data-<description)'
   ),
   array(
      'name'=<'type',
      'type'=<'raw',
      'value'=<'Chtml::encode($data-<type)',
       
   ),
   array(
      'name'=<'link',
      'type'=<'raw',
      'value'=<'$data-<link'
   ),
    
 
)
));

Alternative Way to make Dropdown menu in yii

Alternative Way to make Dropdown menu in yii


 
<div class="row">
  <?php echo $form->dropDownList($model,'country_id',
   CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
   array('empty'=>'Select Country'))?>
 </div>
Or other option
<div class="row">
  <?php echo CHtml::dropDownList('Users[country_id'],'',
   CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
   array('empty'=>'Select Country'))?>
 </div>
 

Related Post