Showing posts with label Simple Task. Show all posts
Showing posts with label Simple Task. Show all posts

One Page Template Scrolling Script

One Page Template Scrolling Script


Hi Today discussed Bootstrap template one page template Scrollig Script url passing id and the scroll script.Follow us script.

One Page Template Scrolling Script
One Page Template Scrolling Script


JavaScript

<script type="text/javascript">
!function(t){"use strict";t("a.page-scroll").bind("click",function(a){var o=t(this);t("html, body").stop().animate({scrollTop:t(o.attr("href")).offset().top-50},1250,"easeInOutExpo"),a.preventDefault()}),t("body").scrollspy({target:".navbar-fixed-top",offset:51}),t(".navbar-collapse ul li a").click(function(){t(".navbar-toggle:visible").click()}),t("#mainNav").affix({offset:{top:100}})}(jQuery);
</script>

angularjs single line json data how to display table format split \r\n

angularjs single line json data how to display table format split \r\n






Hi Today Discussed i handle one task default angularjs single line json data how to display table format split \r\n json data single line json data split \r\n first \r\n table heading <th> tag another table data  <td> followus code.

angularjs single line json data how to display table format split \r\n
angularjs single line json data how to display table format split \r\n

 index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="Jsondatadisplay">
    <div class="container">
  
      <br>
        <h3>Data Details:</h3>
        <table class="table table-striped" id="myTable2">
            <thead>
            <tr>
                <th data-ng-repeat="tr in tableHeader track by $index">{{tr}}</th>
            </tr>
            </thead>
            <tr data-ng-repeat="data in tableData track by $index">
                <td data-ng-repeat="col in data track by $index">{{ col }}</td>

            </tr>
        </table>

        <div>

        </div>

        <script>
            var app = angular.module('myApp', []);
            app.controller('Jsondatadisplay', function ($scope, $http) {
            
                $http
                    .get("data.json")
                    .then(function (res) {
                        var dataToParse = res.data.Data;
                        var replaced = dataToParse.split("\r\n");
                        $scope.tableHeader = replaced[1].split(",");
                        var tempArray = [];
                        angular.forEach(replaced, function (element) {
                            tempArray.push(element.split(","));
                        });

                        delete tempArray[0];
                        delete tempArray[1];
                        $scope.tableData = tempArray;
                    })
            });
        </script>

</body>
</html>
data.json

json data very largest json data so please click github link and download file Click Here

output Click Here

How to Import and Export CSV Files Using PHP and MySQL

How to Import and Export CSV Files Using PHP and MySQL


Hi Today discussed PHP Server side Scripting Language How to Import and Export CSV Files using PHP and mysql. Database normally insert and update and delete queries and bulk insert it's means csv file same column file data csv file data insert mysql. code follows.


How to Import and Export CSV Files Using PHP and MySQL
How to Import and Export CSV Files Using PHP and MySQL



First Create database and then create table.

CREATE DATABASE employee
Create table

CREATE TABLE employeedetils(
eid VARCHAR(50) UNSIGNED PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
create_date VARCHAR(50)
)
dbconnect

<?php
function getdb(){
$servername = "localhost";
$username = "root";
$password = "";
$db = "employee";

try {
   
    $conn = mysqli_connect($servername, $username, $password, $db);
     //echo "Connected successfully"; 
    }
catch(exception $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
    return $conn;
}
?>
PHP File Import function phpfiles.php

<?php


 if(isset($_POST["Import"])){
  
  $filename=$_FILES["file"]["tmp_name"];  


   if($_FILES["file"]["size"] > 0)
   {
     $file = fopen($filename, "r");
         while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
          {


            $sql = "INSERT into employeedetils(eid,firstname,lastname,email,create_date)                    values ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[3]."','".$getData[4]."')";
                   $result = mysqli_query($con, $sql);
    if(!isset($result))
    {
     echo "<script type=\"text/javascript\">
       alert(\"Invalid File:Please Upload CSV File.\");
       window.location = \"index.php\"
        </script>";  
    }
    else {
       echo "<script type=\"text/javascript\">
      alert(\"CSV File has been successfully Imported.\");
      window.location = \"index.php\"
     </script>";
    }
          }
   
          fclose($file); 
   }
 }  


 ?>

View Page design bootstrap lib include

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
View Page


<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>

</head>

<body>
    <div id="wrap">
        <div class="container">
            <div class="row">

                <form class="form-horizontal" action="phpfiles.php" method="post" name="upload_excel" enctype="multipart/form-data">
                    <fieldset>

                        <!-- Form Name -->
                        <legend>Form Name</legend>

                        <!-- File Button -->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="filebutton">Select File</label>
                            <div class="col-md-4">
                                <input type="file" name="file" id="file" class="input-large">
                            </div>
                        </div>

                        <!-- Button -->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="singlebutton">Import data</label>
                            <div class="col-md-4">
                                <button type="submit" id="submit" name="Import" class="btn btn-primary button-loading" data-loading-text="Loading...">Import</button>
                            </div>
                        </div>

                    </fieldset>
                </form>

            </div>
            <?php
               getdbrecords();
            ?>
        </div>
    </div>
</body>

</html>
view php records

function getdbrecords(){
    $con = getdb();
    $Sql = "SELECT * FROM employeedetils";
    $result = mysqli_query($con, $Sql);  


    if (mysqli_num_rows($result) > 0) {
     echo "<div class='table-responsive'><table id='myTable' class='table table-striped table-bordered'>
             <thead><tr><th>EMP ID</th>
                          <th>First Name</th>
                          <th>Last Name</th>
                          <th>Email</th>
                          <th>Registration Date</th>
                        </tr></thead><tbody>";


     while($row = mysqli_fetch_assoc($result)) {

         echo "<tr><td>" . $row['eid']."</td>
                   <td>" . $row['firstname']."</td>
                   <td>" . $row['lastname']."</td>
                   <td>" . $row['email']."</td>
                   <td>" . $row['create_date']."</td></tr>";        
     }
    
     echo "</tbody></table></div>";
     
} else {
     echo "you have no records";
}
}

Export MySQL to CSV With PHP

<div>
            <form class="form-horizontal" action="phpfiles.php" method="post" name="upload_excel"   
                      enctype="multipart/form-data">
                  <div class="form-group">
                            <div class="col-md-4 col-md-offset-4">
                                <input type="submit" name="Export" class="btn btn-success" value="export to excel"/>
                            </div>
                   </div>                    
            </form>           
 </div>
Export Functions

if(isset($_POST["Export"])){
   
      header('Content-Type: text/csv; charset=utf-8');  
      header('Content-Disposition: attachment; filename=data.csv');  
      $output = fopen("php://output", "w");  
      fputcsv($output, array('ID', 'First Name', 'Last Name', 'Email', 'Joining Date'));  
      $query = "SELECT * from employeedetils ORDER BY emp_id DESC";  
      $result = mysqli_query($con, $query);  
      while($row = mysqli_fetch_assoc($result))  
      {  
           fputcsv($output, $row);  
      }  
      fclose($output);  
 }  

PHP database while loop value alphabetically view

PHP database while loop value alphabetically view


PHP database while loop value alphabetically view
PHP database while loop value alphabetically view

Today Discussed PHP database while loop value alphabetical Order view how to display this task is view looks nice view and order based view a database value flows this code.

mysql queris: 

$query = "SELECT `primaryid`,`fieldname`,LEFT(`fieldname`, 1) AS `first_char` FROM tbl_name WHERE (UPPER(`fieldname`) BETWEEN 'A' AND 'Z' OR `fieldname` BETWEEN '0' AND '9') ORDER BY `fieldname`"
$queryresult = mysql_query($query);                                          $current_char = '';
                                                                           while ($row = mysql_fetch_assoc($queryresult)) {                       if ($row['first_char'] != $current_char) {
                        $current_char = $row['first_char'];

                        echo '<div class="clearfix"></div><h1>' . strtoupper($current_char) . '</h1>' . '<br />-----<br />';
                    }                                                     <?php echo stripslashes($row['fieldname']); } ?>
Copy and Paste this code this code is example modify queriys field name is your database table current fieldname and tbl_name is your database table name just replace this field. and another part of code is whill loop displaying looping function try this code and more example click here

Prevent SQL injection in Codeigniter (CI)

Prevent SQL injection in Codeigniter (CI)


SQL injection is an attack made on database query.  In PHP, we are use mysql_real_escape_string()
function to prevent this along with other techniques but codeigniter provides inbuilt function and libraries to prevent this.Join Queries

Prevent SQL injection in Codeigniter (CI)
Prevent SQL injection in Codeigniter (CI)


We can prevent SQL Injection in CodeIgniter in the following three ways  

Escaping Queries
Query Biding
Active Record Class



Escaping Queries
<?php
$name = $this->input->post('uname');
$cn = 'SELECT * FROM tbl_users WHERE user_name='.$this->db->escape($name);
$this->db->query($cn);
?> 
Here $this->db->escape() determines the data type so that it can escape only string data.
It also automatically adds single quotes around the data so you don’t have to do that as well.

Preventing SQL injection in Codeigniter using Query Binding Method 

<?php
    $sql = "SELECT * FROM subscribers_tbl WHERE status = ? AND email= ?";
    $this->db->query($sql, array('active', 'dev2tricks.com.in'));
?>
The query are automatically replaced with the values in the array in the second parameter of the query function.

in Query Binding Method, you don’t have to escape the values manually as it will automatically do that for you.


Preventing SQL injection in Codeigniter using Active Record Class

<?php
   $this->db->get_where('subscribers_tbl',array('status' => 'active','email' => 'dev2tricks.com.in'));
?>

How to create and download a csv file from php script?

How to create and download a csv file from php script?

Today discussed just core php while loop some data stored and display more then data just export download csv or pdf other format document. Here i try this code. this example code format csv export data.
How to create and download a csv file from php script?
How to create and download a csv file from php script?

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line)
}
header dialog you will have to  send http header like this example header

header('Content-Disposition: attach
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}
array_to_csv_download(array(
  array(1,2,3,4), // this array is going to be the first row
  array(1,2,3,4)), // this array is going to be the second row
  "numbers.csv"
);


Instead of the php://memory you can  also use the php://output for the file descriptor and do away with the seeking and such
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}   

Codeigniter Ajax Pagination


Codeigniter Ajax Pagination

Codeigniter Ajax Pagination today solve this task so just share with your. Today we will discuss how to create ajax pagination in Codeigniter Framework. Codeigniter have the pagination library by default.  But many times we are needed to implemented ajax based pagination in codeigniter. and pagination responsive design you implemented your own designed.

Already we discussed codeigniter framework and other related topics so just go the task at first we need to add ajax pagination into the Codeigniter Pagination library.  Copy the Codeigniter pagination library and modify with ajax pagination code.  Rename the Pagination Class to Ajaxpagination and insert the Ajaxpagination.php file into the library folder.  you can download the CodeIgniter Ajax pagination library from the Click Here

   
Codeigniter Ajax Pagination
Codeigniter Ajax Pagination
First Create table


CREATE TABLE `dent_adminusers` (
  `id` int(11) NOT NULL auto_increment,
  `adminname` varchar(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `status` enum('Active','Suspend','Deactive') NOT NULL default 'Deactive',
  `mailstatus` enum('0','1') NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Controller

Create a controller file named posts.php with Posts classed. Into the __construct() function we need to load post model.  Ajaxpagination library. And we set the per page data limit into the $this-perPage variable.


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Posts Management class created by CodexWorld
 */
class Posts extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->model('post');
        $this->load->library('Ajaxpagination');
        $this->perPage = 1;
    }
    
    public function index()
    {
        $data = array();
        
        //total rows count
        $totalRec = count($this->post->getRows());
        
        //pagination configuration
        $config['first_link']  = 'First';
        $config['div']         = 'postList'; //parent div tag id
        $config['base_url']    = base_url().'posts/ajaxPaginationData';
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
        
        $this->ajax_pagination->initialize($config);
        
        //get the posts data
        $data['posts'] = $this->post->getRows(array('limit'=>$this->perPage));
        
        //load the view
        $this->load->view('posts/index', $data);
    }
    
    function ajaxPaginationData()
    {
        $page = $this->input->post('page');
        if(!$page){
            $offset = 0;
        }else{
            $offset = $page;
        }
        
        //total rows count
        $totalRec = count($this->post->getRows());
        
        //pagination configuration
        $config['first_link']  = 'First';
        $config['div']         = 'postList'; //parent div tag id
        $config['base_url']    = base_url().'posts/ajaxPaginationData';
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
        
        $this->ajax_pagination->initialize($config);
        
        //get the posts data
        $data['posts'] = $this->post->getRows(array('start'=>$offset,'limit'=>$this->perPage));
        
        //load the view
        $this->load->view('posts/ajax-pagination-data', $data, false);
    }
}


Model:

Codeigniter Ajax Pagination Create a Model file follows Code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends CI_Model{
    
    function __construct() {
        $this->postTable = 'posts';
    }
    
    function getRows($params = array())
    {
        $this->db->select('*');
        $this->db->from($this->postTable);
        $this->db->order_by('created','desc');
        
        if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit'],$params['start']);
        }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit']);
        }
        
        $query = $this->db->get();
        
        return ($query->num_rows() > 0)?$query->result_array():FALSE;
    }
}
?>


View

Codeigniter Ajax Pagination responsive or your design modify view page.


<h1>Posts</h1>
<div id="container">
    <ul class="list" id="postList">
        <?php if(!empty($posts)): foreach($posts as $post): ?>
        <li>
            <p><b>Title:</b>&nbsp;<?php echo $post['title']?></p>
            <p><b>Content:</b>&nbsp;<?php echo $post['content']?></p>
            <p><b>Created:</b>&nbsp;<?php echo $post['created']?></p>
        </li>
        <?php endforeach; else: ?>
        <li class="err_msg">Post(s) not available.</li>
        <?php endif; ?>
        <?php echo $this->ajax_pagination->create_links(); ?>
    </ul>
</div>

Angularjs Sign In Via OAuth

Angularjs Sign In Via OAuth

What is OAuth ?

OAuth is a thired party access this means OAuth is a protocol to allow secure authorization in a simple and standred method from web, mobile and other device Applications.  As an application developer, services that provider HTTP APIs supporting OAuth, let you access parts of their services on behalf of your users. Example your websites Login Authorizations when accessing  a social media if your user gives you permission to access his account you might be able to import picture and friend list to your application.

This tutorial focuses on using OAuth to implement Sign-In through the following providers: Facebook, Google+, LinkedIn, and Twitter. These providers use either OAuth1.0a (LinkedIn, Twitter) or OAuth2.0 (Facebook, Google+).

Facebook

1.Create a new Facebook App.
2.The app will be assigned an App ID and App Secret. In the Settings panel, make sure to set the App Domains to the domain your Kinvey app is running on.

Angularjs Sign In Via OAuth
Facebook App
3.Use the App ID to load the Facebook SDK in your application. Please see Using Facebook Social Identity for more information.

Google
  1. Create a new Google platform.
  2. Select your newly created Google platform and select APIs & auth → Credentials
  3. Under OAuth click Create new Client ID and select Web Application. Make sure to set the Authorized Redirect URIs and Authorized JavaScript Origins to the domain for your Kinvey app. Click Create Client ID when you are finished.
  4. The app will be assigned a Client ID and Client secret.
Google API
Google API
Create Client Id

Google Client id
Google Cliend id

5.Return to the data browser. Manually add the Google provider and your Google application credentials:

 {
     "provider"        : "google",
     "consumer_key"    : "949921934567-gp8qc0cqv87ce6jfhoom1q8jk6634567.apps.googleusercontent.com",
     "consumer_secret" : "pKT1_ONG55uHAxE2zDDSAT7"
 }
6.The Data Browser should now contain the Google provider similar to the image below.


google json data
api



Same Method Linked and Twitter API Generate.

// OAuth providers.
var urlConfig = {
  // OAuth1.0a.
  requestToken: {
    linkedIn : 'https://api.linkedin.com/uas/oauth/requestToken',
    twitter  : 'https://api.twitter.com/oauth/request_token'
  },

   // OAuth1.0a and 2.0.
  authenticate: {
    google   : 'https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile',
    linkedIn : 'https://api.linkedin.com/uas/oauth/authenticate',
    twitter  : 'https://api.twitter.com/oauth/authenticate'
  }
};
asdfsdf


var tokenize = function(string) {
  var tokens = {};
  string.split('&').forEach(function(pair) {
    var segments = pair.split('=', 2).map(decodeURIComponent);
    if(segments[0]) {// Key must be non-empty.
      tokens[segments[0]] = segments[1];
    }
  });
  return tokens;
};
/**
 * Logs in or creates user with provided OAuth1.0a credentials.
 *
 * @param {Object} doc OAuth provider document.
 * @param {Object} request Kinvey request object.
 * @param {Object} response Kinvey response object.
 * @param {Object} modules Available JavaScript libraries.
 */
var login = function(doc, request, response, modules) {
  // Validate request body.
  var provider = doc.provider;
  if(!(request.body._socialIdentity && request.body._socialIdentity[provider] && request.body._socialIdentity[provider].access_token && request.body._socialIdentity[provider].access_token_secret)) {
    response.body = {
      error       : 'IncompleteRequestBody',
      description : 'The request body is either missing or incomplete.',
      debug       : 'Missing required attributes: _socialIdentity.<provider>.[access_token, access_token_secret]'
    };
    return response.complete(400);
  }
  // Add consumer key and secret to request body.
  request.body._socialIdentity[provider].consumer_key    = doc.consumer_key;
  request.body._socialIdentity[provider].consumer_secret = doc.consumer_secret;
  // Forward request to the login endpoint.
  modules.request.post({
    uri: 'https://' + encodeURIComponent(request.headers.host) + '/user/' + encodeURIComponent(request.username) + '/login',
    headers: {
      Authorization          : request.headers.authorization,// Application credentials.
      'Content-Type'         : 'application/json',
      'X-Kinvey-API-Version' : request.headers['x-kinvey-api-version']
    },
    json: request.body
  }, function(err, res) {
    if(err) {// Request failed.
      modules.logger.error(err);
      response.body = {
        error       : 'BLInternalError',
        description : 'The Business Logic script did not complete. See debug message for details.',
        debug       : err.code
      };
      response.complete(550);
    }
    else {// Forward response.
      response.body = res.body;
      response.complete(res.status);
    }
  });
};
/**
 * Obtains an OAuth1.0a request token.
 *
 * @param {Object} doc OAuth provider document.
 * @param {Object} request Kinvey request object.
 * @param {Object} response Kinvey response object.
 * @param {Object} modules Available JavaScript libraries.
 */
var requestOAuth1Token = function(doc, request, response, modules) {
  // Validate request body.
  var provider = doc.provider;
  if(!request.body.redirect) {
    response.body = {
      error       : 'IncompleteRequestBody',
      description : 'The request body is either missing or incomplete.',
      debug       : 'Missing required attributes: redirect'
    };
    return response.complete(400);
  }
  // Fire request.
  modules.request.post({
    uri: urlConfig.requestToken[provider],
    oauth: {
      callback: request.body.redirect,
      consumer_key: doc.consumer_key,
      consumer_secret: doc.consumer_secret
    }
  }, function(err, res) {
    if(err) {// Request failed.
      modules.logger.error(err);
      response.body = {
        error       : 'BLInternalError',
        description : 'The Business Logic script did not complete. See debug message for details.',
        debug       : err.code
      };
      response.complete(550);
    }
    else if(200 !== res.status) {// Tokens are invalid.
      response.body = {
        error       : 'InvalidCredentials',
        description : 'Invalid credentials. Please retry your request with correct credentials.',
        debug       : res.body
      };
      response.complete(401);
    }
    else {// Tokens are valid.
      var tokens = tokenize(res.body);
      response.body = {
        url: urlConfig.authenticate[provider] + '?oauth_token=' + encodeURIComponent(tokens.oauth_token),
        oauth_token: tokens.oauth_token,
        oauth_token_secret: tokens.oauth_token_secret
      };
      response.complete(200);
    }
  });
};
/**
 * Obtains an OAuth2 access token.
 *
 * @param {Object} doc OAuth provider document.
 * @param {Object} request Kinvey request object.
 * @param {Object} response Kinvey response object.
 * @param {Object} modules Available JavaScript libraries.
 */
var requestOAuth2Token = function(doc, request, response, modules) {
  // Validate request body.
  var provider = doc.provider;
  if(!request.body.redirect) {
    response.body = {
      error       : 'IncompleteRequestBody',
      description : 'The request body is either missing or incomplete.',
      debug       : 'Missing required attributes: redirect'
    };
    return response.complete(400);
  }
  // Build URL.
  var url = urlConfig.authenticate[provider] +
    '&client_id=' + encodeURIComponent(doc.consumer_key) +
    '&response_type=token' +
    '&redirect_uri=' + encodeURIComponent(request.body.redirect);
  if(request.body.state) {// Append state if specified.
    url += '&state=' + encodeURIComponent(request.body.state);
  }
  // No network request needed, return instantly.
  response.body = { url: url };
  response.complete(200);
};
/**
 * Verifies the OAuth1.0a request token.
 *
 * @param {Object} doc OAuth provider document.
 * @param {Object} request Kinvey request object.
 * @param {Object} response Kinvey response object.
 * @param {Object} modules Available JavaScript libraries.
 */
var verifyToken = function(doc, request, response, modules) {
  // Validate request body.
  var provider = doc.provider;
  if(!(request.body.oauth_token && request.body.oauth_token_secret && request.body.oauth_verifier)) {
    response.body = {
      error       : 'IncompleteRequestBody',
      description : 'The request body is either missing or incomplete.',
      debug       : 'Missing required attributes: oauth_token, oauth_token_secret, and/or oauth_verifier'
    };
    return response.complete(400);
  }
  // Verify request.
  modules.request.post({
    uri: urlConfig.accessToken[provider],
    oauth: {
      consumer_key: doc.consumer_key,
      consumer_secret: doc.consumer_secret,
      token: request.body.oauth_token,
      token_secret: request.body.oauth_token_secret,
      verifier: request.body.oauth_verifier
    }
  }, function(err, res) {
    if(err) {// Request failed.
      modules.logger.error(err);
      response.body = {
        error       : 'BLInternalError',
        description : 'The Business Logic script did not complete. See debug message for details.',
        debug       : err.code
      };
      response.complete(550);
    }
    else if(200 !== res.status) {// Tokens are invalid.
      response.body = {
        error       : 'InvalidCredentials',
        description : 'Invalid credentials. Please retry your request with correct credentials.',
        debug       : res.body
      };
      response.complete(401);
    }
    else {// Tokens are valid.
      var tokens = tokenize(res.body);
      response.body = {
        access_token        : tokens.oauth_token,
        access_token_secret : tokens.oauth_token_secret
      };
      response.complete(200);
    }
  });
};
/**
 * onPreSave hook. Routes OAuth related requests.
 *
 * @param {Object} request Kinvey request object.
 * @param {Object} response Kinvey response object.
 * @param {Object} modules Available JavaScript libraries.
 */
var onPreSave = function(request, response, modules) {
  var provider = request.params.provider;
  if(null != provider) {
    modules.collectionAccess.collection('oauth').findOne({ provider: provider }, function(err, doc) {
      if(err) {// Request failed.
        modules.logger.error(err);
        response.body = {
          error       : 'BLInternalError',
          description : 'The Business Logic script did not complete. See debug message for details.',
          debug       : err.code
        };
        response.complete(550);
      }
      else if(null == doc) {// Provider not supported.
        response.body = {
          error       : 'FeatureUnavailable',
          description : 'This OAuth provider is not supported by this application.',
          debug       : ''
        };
        response.complete(400);
      }
      else {// Provider found.
        // Route step.
        var step = request.params.step || 'login';
        var oauth1 = -1 !== ['linkedIn', 'twitter'].indexOf(provider);
        var oauth2 = -1 !== ['google'].indexOf(provider);
        // OAuth1.0a providers support login through this proxy.
        if(oauth1 && -1 !== ['login'].indexOf(step)) {
          login(doc, request, response, modules);
        }
        // Request a token.
        else if(oauth1 && 'requestToken' === step) {
          requestOAuth1Token(doc, request, response, modules);
        }
        else if(oauth2 && 'requestToken' === step) {// OAuth2.
          requestOAuth2Token(doc, request, response, modules);
        }
        // OAuth1.0a providers require the request token to be verified.
        else if(oauth1 && 'verifyToken' === step) {
          verifyToken(doc, request, response, modules);
        }
        // Provider/step combination not supported.
        else {
          response.body = {
            error       : 'BadRequest',
            description : 'Unable to understand request.',
            debug       : 'The provided step is not valid in combination with this provider.'
          };
          response.complete(400);
        }
      }
    });
  }
  else {
    // Patch regular save requests by embedding the `consumer_key` and
    // `consumer_secret` for OAuth1.0a providers.
    if(request.body && request.body._socialIdentity) {
      var oAuth1Provider = null;
      var socialIdentity = request.body._socialIdentity;
      if(socialIdentity.twitter && socialIdentity.twitter.access_token) {
        oAuth1Provider = 'twitter';
      }
      else if(socialIdentity.linkedIn && socialIdentity.linkedIn.access_token) {
        oAuth1Provider = 'linkedIn';
      }
      // Patch.
      if(null !== oAuth1Provider) {
        return modules.collectionAccess.collection('oauth').findOne({ provider: oAuth1Provider }, function(err, doc) {
          if(err) {// Request failed.
            modules.logger.error(err);
            response.body = {
              error       : 'BLInternalError',
              description : 'The Business Logic script did not complete. See debug message for details.',
              debug       : err.code
            };
            response.complete(550);
          }
          else if(null == doc) {// Provider not supported.
            response.body = {
              error       : 'FeatureUnavailable',
              description : 'This OAuth provider is not supported by this app.',
              debug       : ''
            };
            response.complete(400);
          }
          else {// Provider found.
            request.body._socialIdentity[oAuth1Provider].consumer_key    = doc.consumer_key;
            request.body._socialIdentity[oAuth1Provider].consumer_secret = doc.consumer_secret;
            response['continue']();
          }
        });
      }
    }
    // Regular request, continue.
    response['continue']();
  }
};

How to send email with CodeIgniter

How to send email with CodeIgniter


How to send email with CodeIgniter
How to send email with CodeIgniter
Today I have solve this task share with you codeigniter Mail Function Send a Mail I am  First time Implementing MVC Structure.  Following Code. Session Storage



View.html

<form action="<?php echo base_url('index.php/email/mysend_mail'); ?>" method="post">
Please, enter e-mail: <input type="text" name="e-mail"><input type="submit" name="submit" value="Submit">
</form>

Controller

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

class Email extends CI_Controller {

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

public function index()
{

$this->load->view('header');
    $this->load->view('email_form');
    $this->load->view('footer');
}
  
  public function mysend_mail(){
    $this->load->helper('url');

    if (!isset($_POST['e-mail'])){
      //redirect if no parameter e-mail
      redirect(base_url());
    };

    //load email helper
    $this->load->helper('email');
    //load email library
    $this->load->library('email');
    
    //read parameters from $_POST using input class
    $email = $this->input->post('e-mail',true);    
  
    // check is email addrress valid or no
    if (valid_email($email)){  
      // compose email
      $this->email->from($email , 'xxxxx');
      $this->email->to($email); 
      $this->email->subject('My First CodeIgniter Email Example');
      $this->email->message('CodeIgniter Email Example App!');  
      
      // try send mail ant if not able print debug
      if ( ! $this->email->send())
      {
        $data['message'] ="Email not sent \n".$this->email->print_debugger();      
        $this->load->view('header');
        $this->load->view('message',$data);
        $this->load->view('footer');

      }
         // successfull message
        $data['message'] ="Email was successfully sent to $email";
      
        $this->load->view('header');
        $this->load->view('message',$data);
        $this->load->view('footer');
    } else {

      $data['message'] ="Email address ($email) is not correct. Please <a href=".base_url().">try again</a>";
      
      $this->load->view('header');
      $this->load->view('message',$data);
      $this->load->view('footer');
    }

  }
  
  public function info(){
    phpinfo();
  }
    
}

Ionic Framework Session Controller

Ionic Framework Session Controller

Ionic Framework Session 

Ionic Framework Session Controller is two controllers you create in this module use the Session service defined in the starter.services module. To add starter.services as a dependency to the starter.controller module:

  1. Open conference/www/js/controllers.js
  2. Add starter.services as a dependency to make the Session service available to the controllers:
angular.module('starter.controllers', ['starter.services'])

Implement the Session

  1. In controllers.js, delete PlayListsCtrl (plural)
  2. Replace it with a controller named SessionsCtrl that retrieves the list of conference sessions using the Session service and stores it in a scope variable named sessions:
.controller('SessionsCtrl', function($scope, Session) {
    $scope.sessions = Session.query();
})
or

.controller('SessionCtrl', function($scope, $stateParams, Session) {
    $scope.session = Session.get({sessionId: $stateParams.sessionId});
});
Ionic Framework Session stored and Login your username Ionic Login Authentication Click Here

Wordpress Include Functions

Wordpress Functions


First Header Include header.php template files from your current theme's directory.  If a name is specified then a specialised header- name.php  will be included.
Wordpress Functions
Wordpress Functions


Header Functions

<?php get_header( $name );  ?>

Single Header

<?php get_header(); ?>
<h2>Error 404 - Not Found</h2>
<?php get_sidebar(); ?>
<?php get_footer(); ?>


Multiple Header

<?php
if ( is_home() ) :
get_header( 'home' );
elseif ( is_404() ) :
get_header( '404' );
else :
get_header();
endif;
?>

Sidebar

get_sidebar ( string $name = null )

Load sidebar template.

Includes the sidebar template for a your theme or if a name specified then a specialised sidebar will be included. For the parameter, if the file is called “sidebar-special.php” then specify “special”.

<?php get_sidebar('my-bar'); ?>

Sidebar Left and Right


<?php get_header(); ?>
<?php get_sidebar( 'left' ); ?>
<?php get_sidebar( 'right' ); ?>
<?php get_footer(); ?>



Comments_template Functions

comments_template ( string $file = '/comments.php', bool $separate_comments = false )


function comments_template( $file = '/comments.php', $separate_comments = false ) {
    global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage;

    if ( !(is_single() || is_page() || $withcomments) || empty($post) )
        return;

    if ( empty($file) )
        $file = '/comments.php';

    $req = get_option('require_name_email');



<?php comments_template( '/short-comments.php' ); ?>

<?php comments_template( '/custom-templates/alternative-comments.php' ); ?> 

Angularjs xeditable

Angular-xeditable – Edit in place for AngularJS

Angular xeditable
Angularjs xeditable
Angular-xeditable is a bundle of AngularJS directives that allows you to create editable elements.
Such technique is also known as click-to-edit or edit-in-place. Angularj file upload

Controls & Features

text
textarea
select
checkbox
radio
date
time
html5 inputs
typeahead

How to set x-editable select box

Angularjs xeditable is key features select box is confused so i mentioned select box xeditable code follows and database insert data
<span editable-select="active.ClientQueries" e-name="ClientQueries" e-ng-options="s for s in main.states">{{ (states | filter:{value: active.ClientQueries})[0].text || 'Not set' }}</span>
AngularJS X-Editable table row validation

<tr ng-repeat="user in pagedTel.data | filter:searchField | orderBy:sortType:sortReverse" ng-if="pagedTel.data.length > 0">
    <td>
        <div ng-show="rowform.$visible">
            <form editable-form name="rowform" onaftersave="upd_tel($data, user.id)">
                <button type="submit" class="bt-t bt-suc"><i class="fa fa-check"></i></button><button type="button" ng-click="rowform.$cancel()" class="bt-t bt-dan"><i class="fa fa-times"></i></button>
            </form>
        </div>
        <div ng-show="!rowform.$visible">
            <a class="bt-t bt-war"><i class="lgicon icon icon-pencil" ng-click="rowform.$show()"></i></a><a class="bt-t bt-dan"><i class="lgicon icon icon-trash" id="{{user.id}}" ng-click="openDialog(user.id)"></i></a>
        </div>
    </td>

    <td>
        <span editable-text="myTel.ds_contato" e-name="ds_contato" e-form="rowform" onbeforesave="checkData($data)" e-required>
            {{user.ds_contato}}
        </span>
    </td>

    <td>
        <span editable-text="myTel.num_tel" e-name="num_tel" e-form="rowform" e-mask="(99) 9?9999-9999" e-required onbeforesave="checkTel($data)">
            {{user.num_tel}}
        </span>
    </td>
</tr>
Controller


$scope.checkData = function(data) {
    if (data == null) {
        return "Required field";
    };
};

$scope.checkTel = function(data) {
    if (data == null) {
        return "Required field";
    } else if ($scope.rowform.user.$invalid) {
        return "Invalid field";
    }
};
Example xeditable Code:

First include Angularjs in your project
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
Second Include Bootstrap css
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
Third Install angular-xeditable bower
bower install angular -xeditable
Include angular xeditable into your project
<link href="bower_components/angular-xeditable/dist/css/xeditable.css" rel="stylesheet">
<script src="bower_components/angular-xeditable/dist/js/xeditable.js"></script>
Define angular app and add xeditable to depandencies
<html ng-app="myapp">
var app = angular.module("myapp",["xeditable"]);
Set theme in app.run:
app.run(function(editableOptions) {
  editableOptions.theme = 'bs3'; });
view.html
<div ng-controller="Ctrl">
  <a href="#" editable-text="user.name">{{ user.name || "empty" }}</a>
</div>
Controller.js
app.controller('Ctrl', function($scope) {
  $scope.user = {
    name: 'Dev2tricks'
  };  
});

Wordpress Shopping cart Installation

How to Use WP Shopping Cart


Wordpress Shopping cart
Wordpress Shopping cart


Add the shopping cart to your theme.


Copy wp-shopping-cart.php to your theme directory. Call the shopping cart in your functions.php file: Normal PHP shopping car

require_once('wp-shopping-cart.php');

Configure your settings.

In the wp-shopping-cart.php file, replace these variables with your information:
$paypal_account - Your PayPal email address
$cart_icon - An icon for your shopping cart link, if you have one
$url_store - The URL of your store
$url_cart - The URL of your shopping cart
$url_update - The meta info/URL when the cart is updated
$url_success - The meta info/URL when the checkout is successful
Shipping variables - Based on shopping cart subtotal value

 Create product pages.

Create pages for your products, and use the [add_to_cart] shortcode to create links.

Shortcode variables:
product="PRODUCT NAME"
price="X.XX"
options="TITLE=OPTION 1|OPTION 2|OPTION 3" (Not required. Limit 1 set of options.)
sold="SOLD OUT MESSAGE"

Example:
[add_to_cart product="T-Shirt" price="20" options="Size=Small|Med|Large"]

Create a shopping cart page.

Create a shopping cart page, and use the [checkout_cart] shortcode to embed a cart.


 Add a link to the cart.

Add a link to the cart anywhere on your site using the [checkout_cart_link] shortcode or <?php echo checkout_cart_link(); ?>.

Another Method

WP Shopping Cart Installation


  • Unzip and Upload the folder “wordpress-paypal-shopping-cart” to the “/wp-content/plugins/” directory.
  • Activate this Plugin
  • Go to settings and configure the options your peyment method paypal email,shopping cart and return url etc
  • Use the shortcode to add a product a post or page where you want it to appear

WP Shopping Cart

To add the ‘Add to Cart’ button simply insert the following shortcode to a post or page next to the product description:

[wp_cart_button name="PRODUCT-NAME" price="PRODUCT-PRICE"]

Replace PRODUCT-NAME and PRODUCT-PRICE with the actual name and price.

Here is an example usage of the shortcode:

[wp_cart_button name="Test Product" price="19.95"]
To add the shopping cart to a post or page, insert the following shortcode to a post or page.

[show_wp_shopping_cart]
Using Button and Cart Form a template File

To Add 'Add Cart Button' from template.php file use this code:
<?php echo print_wp_cart_button_for_product('PRODUCT-NAME', PRODUCT-PRICE); ?>
<?php echo print_wp_cart_button_for_product('wordpress', 7.50); ?>
To add the shopping cart to the sidebar, simply use the widget from the widgets menu or add the following line to your sidebar template file where you want the shopping cart to appear

<?php echo print_wp_shopping_cart() ?>