Thursday, June 2, 2016

ajax page for crawler using history.pushState and window.onpopstate

<!DOCTYPE html>
<!-- saved from url=(0045)http://html5doctor.com/demos/history/whiskers -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
  <title>test!</title>
  <style>
    html { background-color:#ddd; }
    body { margin:1em auto; max-width:600px; background-color:#fff; border:solid 1px #aaa; padding:15px; font-family:Georgia,serif; }
    h1 { font-family:Helvetica,Arial,sans-serif; float:left; width:30%; margin:0; }
    nav { display:block; float:right; width:45%;}
    ul { list-style:none; padding:0; margin:0; }
    li { display:inline-block; padding:0; border-right:solid 1px #aaa; margin:.5em 0 0; }
    li:last-child { border-right:0; }
    a { color:rgb(0,144,210); padding:.2em 0.5em; }
    a:hover { text-decoration:none; }
    #content { clear:left; float:left; width:45%; margin-right:10%; line-height:1.4em; }
    #photo { float:right; width:45%; margin-top:1em; }
    .cf:before, .cf:after { content:""; display:table; }
    .cf:after { clear:both; }
  </style>
</head>

<body class="cf">
  <h1>test!</h1>

  <nav>
    <ul class="cf">
      <li><a href="/fluffy">Fluffy</a></li>
      <li><a href="/socks">Socks</a></li>
      <li><a href="/whiskers">Whiskers</a></li>
      <li><a href="/bob">Bob</a></li>
    </ul>
  </nav>

  <p id="content">content!</p>

  <img src="" alt="A heartbreakingly cute kitten!" id="photo">

  <script>
    // Not the most elegant code but fit enough for this example. Enjoy the kitten goodness!
    var contentEl = document.getElementById('content'),
        photoEl = document.getElementById('photo'),
        linkEls = document.getElementsByTagName('a'),
        cats = {
          fluffy: {
            content: 'Fluffy!',
            photo: 'http://placekitten.com/200/200'
          },
          socks: {
            content: 'Socks!',
            photo: 'http://placekitten.com/280/280'
          },
          whiskers: {
            content: 'Whiskers!',
            photo: 'http://placekitten.com/350/350'
          },
          bob: {
            content: 'Just Bob.',
            photo: 'http://placekitten.com/320/270'
          }
        };

    // Switcheroo!
    function updateContent(data) {
      if (data == null)
        return;

      contentEl.textContent = data.content;
      photoEl.src = data.photo;
    }

    // Attach event listeners
    for (var i = 0, l = linkEls.length; i < l; i++) {
      linkEls[i].addEventListener('click', function (event) {
      var cat = event.target.getAttribute('href').split('/').pop();
 var data = cats[cat] || null; // In reality this could be an AJAX request

      updateContent(data);

      // Add an item to the history log
 document.title = event.target.textContent;
      history.pushState(data, event.target.textContent, event.target.href);

      return false;
    });
    }

    // Revert to a previously saved state
    window.addEventListener('popstate', function(event) {
      console.log('popstate fired!');

      updateContent(event.state);
    });

    // Store the initial content so we can revisit it later
    history.replaceState({
      content: contentEl.textContent,
      photo: photoEl.src
    }, document.title, document.location.href);
  </script>



</body></html>

Sunday, May 15, 2016

angularjs too many request queue using promise

angularjs дээр олон тооны request илгээхдээ хүсэлт очиж байгааг дараалийг удирдаж дэс дараалалтай яаж илгээх вэ?

<div ng-app>
  <h2>$q test</h2>
  <div ng-controller="TodoCtrl">
      <div ng-bind="'Promise1: ' + Promise1"></div>
      <div ng-bind="'Promise2: ' + Promise2"></div>
      <div ng-bind="'Promise3: ' + Promise3"></div>
      <div ng-bind="'Promise4: ' + Promise4"></div>
      <div ng-bind="'Promise5: ' + Promise5"></div><br />
      <div ng-bind="'Status1: ' + Status1"></div>
      <div ng-bind="'Status2: ' + Status2"></div>
  </div>

</div>

JS:

function TodoCtrl($scope, $q, $timeout) {
    function createPromise(name, timeout, willSucceed) {
        $scope[name] = 'Running';
        var deferred = $q.defer();
        $timeout(function() {
            if (willSucceed) {
                $scope[name] = 'Completed';
                deferred.resolve(name);
            } else {
                $scope[name] = 'Failed';
                deferred.reject(name);
            }
        }, timeout * 1000);
        return deferred.promise;
    }
    
    // Create 5 promises
    var promises = [];
    var names = [];
    for (var i = 1; i <= 5; i++) {
        var willSucceed = true;
        if (i == 2) willSucceed = false;
        promises.push(createPromise('Promise' + i, i, willSucceed));
    }
    
    // Wait for all promises    
    $scope.Status1 = 'Waiting';
    $scope.Status2 = 'Waiting';
    $q.all(promises).then(
        function() { 
            $scope.Status1 = 'Done'; 
        }, 
        function() { 
            $scope.Status1 = 'Failed'; 
        }
    ).finally(function() {
        $scope.Status2 = 'Done waiting';
    });
}

result:

Promise1: Completed
Promise2: Failed
Promise3: Completed
Promise4: Completed
Promise5: Completed

Status1: Failed
Status2: Done waiting

Wednesday, May 4, 2016

php data array echo to excel file

<?PHP
  $data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
    array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
    array("firstname" => "James", "lastname" => "Brown", "age" => 31),
    array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
    array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
    array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
    array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
  );

  function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // file name for download
  $filename = "website_data_" . date('Ymd') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\n";
      $flag = true;
    }
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\n";
  }

  exit;
?>

Thursday, April 28, 2016

codeigniter my custom captcha controller, view

$config['compress_output'] = TRUE;
****************************************************************

<?php

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

class captcha extends HO_Admin {

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

        //image captcha library
        $this->load->library('HO/HiimelCaptcha', array($this), 'captcha');
    }

    public function image() {
        $this->xhr_protect();

        header("Content-type: image/jpeg");

        $arr = $this->captcha->createImage(6);
        $im = reset(array_values($arr));
        ob_start();
        imagejpeg($im);
        $this->output->cache(0);
        $this->output->set_output('data:image/jpeg;base64,' . base64_encode(ob_get_clean()));
    }

}

******************************************

if ($this->web_cache_minute > 0) {
                $this->output->cache($this->web_cache_minute);
            }
            $this->output->set_output($this->web->page());

********************************************

<div class="captcha">
                <div class="detail">
                    <div class="img">
                        <img src="" alt="" title="captcha">
                    </div>
                    <div class="inp">
                        <input type="text" maxlength="10" id="captcha_code" name="captcha_code">
                        <label>Дуурайж бичээрэй!</label>
                    </div>
                </div>
            </div>
            <script>
                (function reloadCaptchaImg(capimg) {
                    var link = '<?php echo admin_url('captcha/image?'); ?>' + getTimeAsLong();
                    $.ajax({
                        url: link,
                        success: function (result) {
                            var par = capimg.parent();
                            capimg.remove();
                            capimg = $('<img src="' + result + '"/>');
                            capimg.appendTo(par);
                            capimg.animate({'opacity': '1'}, {
                                duration: 300
                            });
                        }
                    });
                })($('.captcha img'));
            </script>