Friday, September 21, 2012

jQuery change browser url, page content, title without loading full page

Its a jQuery technique.

TO CHANGE PAGE URL:
window.history.pushState("object or string", "Title", "/new-url");
 
TO CHANGE PAGE TITLE:
document.title = "NEW PAGE TITLE"; 
 
TO CHANGE PAGE CONTENT:
jQuery("body").html("SUCCESS"); 
 
FOR MORE INFO:
https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history 

Thursday, July 26, 2012

Send Email Using CakePhp 2.0.6 and CakeEmail

Edit app/Config/email.php
public $default = array(
        'transport' => 'Smtp',
        'host' => '',
        'port' => 25,
        'timeout' => 300,
        'username' => '',
        'password' => '',
        'charset' => 'utf-8',
        'headerCharset' => 'utf-8',
    );

Create a component in app/Controller/Component as EmailHandlerServiceComponent.php
<?php
    class EmailHandlerServiceComponent extends Object {
        var $controller;

        public function sendEmail($to = "", $from = "", $fromName = "", $subject = "No Subject", $values = array())
        {
            App::uses('CakeEmail', 'Network/Email');
            $emailSender = new CakeEmail('default');
            $emailSender->to($to);
            $emailSender->subject(utf8Encode($subject));
            $emailSender->from(array($from=>$fromName));
            $emailSender->emailFormat('both');
            $emailSender->viewVars($values);
            $emailSender->template("first", "default");
            if ($emailSender->send()) {
                return true;
            } else {
                return false;
            }
        }
    }
?>

Create a file app/View/Layouts/Emails/html/default.php
Create a file app/View/Layouts/Emails/text/default.php 

Create a file app/View/Emails/html/first.php  
Create a file app/View/Emails/text/first.php 

Call sendEmail() from any controller.

You May Need To Edit app/lib/Cake/Network/Email/CakeEmail.php to set $this->charset and $this->_appCharset, set them to "utf-8" as default. 

Tuesday, July 10, 2012

Change apache port number

Just go to <XAMP LOCATION>\xampp\apache\conf
Open conf.httpd and search for 'Listen' and change port number you wish.

conf.httpd
in browser, add ':81' or your port number after localhost

Sunday, May 20, 2012

Upload file to server using ajax and php

Include jquery.form.js and jquery.min.js

<script type="text/javascript" src="/js/jquery.form.js"></script>
<script type="text/javascript" src="/js/jquery.min.js"></script>

jQuery("#contact-form").ajaxForm({
    beforeSubmit: function() {
        jQuery.showBackgroundWorkingState();
    },
    success: function(data) {
        /*console.log(data);*/
        try {
            if(data == CONSTANT_JS_SUCCESS_CODE) {

            } else {
                jQuery.showWarning("Error uploading file, please try again later.");       
            }
        } catch ( ex ) {
            jQuery.showWarning("Error uploading file, please try again later.");
        }
        jQuery.hideBackgroundWorkingState();
    },
    error: function() {
        jQuery.showWarning("Error uploading file, please try again later.");
        jQuery.hideBackgroundWorkingState();
    }
}).submit(); 
 
File save using php script:

<?php
$name = $_FILES['photoimg']['name'];
list($txt, $ext) = explode(".", $name);
$tmp = $_FILES['photoimg']['tmp_name'];
$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageLocation = $docRoot . "/app/webroot/img/";
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
if(move_uploaded_file($tmp, $imageLocation.$actual_image_name)) {
    die("1");
}
die("0"); 
?>

Image crop using jquery and php

Download jquery plugin from: http://code.google.com/p/jcrop/

create a folder named: crop

create a folder named: css

create a folder named: img

create a folder named: js

move Jcrop.jpg and jquery.Jcrop.min.css to /css folder

move jquery.color.js, jquery.Jcrop.js and jquery.min.js to /js folder

place a image named pool.jpg to /img folder

create a file index.php:

<?php
<link rel="stylesheet" type="text/css" href="/css/jquery.Jcrop.min.css" /> 
<script type="text/javascript" src="/js/jquery.color.js"></script> 
<script type="text/javascript" src="/js/jquery.Jcrop.js"></script>

?>
<img src="/img/pool.jpg" id="cropbox" alt="Flowers" />
<script type="text/javascript">

    jQuery(function($){
        jQuery('#cropbox').Jcrop({
            onChange: showCoords,
            onSelect: showCoords
        });
        function showCoords(c)
        {
            jQuery('#x1').val(c.x);
            jQuery('#y1').val(c.y);
            jQuery('#x2').val(c.x2);
            jQuery('#y2').val(c.y2);
            jQuery('#w').val(c.w);
            jQuery('#h').val(c.h);
        };
        $("#imageResizeValirables").submit(function() {
            var formData = $(this).serialize();
            $.post('/action.php', formData, function(returnData) {
                if(returnData == 'success') {
                    $("#croppedImage").attr("src", "/crop/"+$("#beCroppedImage").attr("value") + "?" + new Date().getTime());
                } else {
                    alert("Try again please.");
                }
            });
        });
    });

</script>

<form onsubmit="return false;" id="imageResizeValirables" class="coords">
    <input type="hidden" id="beCroppedImage" name="img" value="pool.jpg">
    <input type="hidden" size="4" id="x1" name="x1" />
    <input type="hidden" size="4" id="y1" name="y1" />
    <input type="hidden" size="4" id="x2" name="x2" />
    <input type="hidden" size="4" id="y2" name="y2" />
    <input type="hidden" size="4" id="w" name="w" />
    <input type="hidden" size="4" id="h" name="h" />
    <input type="submit" value="Resize">
</form>
<img id="croppedImage" alt='' />

create another file action.php

$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageLocation = $docRoot . "/app/webroot/img/" . $_POST["img"];
$newImageLocation = $docRoot . "/app/webroot/crop/" . $_POST["img"];
 if (file_exists($imageLocation)) {
     list($current_width, $current_height) = getimagesize($imageLocation);
     $x1 = (int) $_POST['x1'];
     $y1 = (int) $_POST['y1'];
     $x2 = (int) $_POST['x2'];
     $y2 = (int) $_POST['y2'];
     $w = (int) $_POST['w'];
     $h = (int) $_POST['h'];

      $crop_width = $w;
      $crop_height = $h;
      $new = imagecreatetruecolor($crop_width, $crop_height);
      $current_image = imagecreatefromjpeg($imageLocation);
      imagecopyresampled($new, $current_image, 0, 0, $x1, $y1, $crop_width, $crop_height, $w, $h);
      imagejpeg($new, $newImageLocation, 100);
      echo "success";
      exit;
 }
 echo "fail";
 exit;

Wednesday, May 16, 2012

Upload Video To Youtube Using Php Script

DOWNLOAD ZEND DATA FROM:
http://framework.zend.com/download/gdata
OR
https://www.box.com/s/e28da8suyty2nc3jtm72
OR
https://docs.google.com/file/d/0B5nZNPW48dpFMTJPMks3WWZtd0E/edit?usp=sharing

set that root folder in project

index.php:

<?php
require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();

Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

session_start();
/* your next url */
$next = 'http://localhost/phpYouTube/welcome.php';
$scope = 'http://gdata.youtube.com';
$secure = false;
$session = true;
$returnData = Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
header("Location: ".$returnData);
?>


welcome.php

<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
        $username = 'name@gmail.com',
        $password = 'password',
        $service = 'youtube',
        $client = null,
        $source = 'MySource', // a short string identifying your application
        $loginToken = null,
        $loginCaptcha = null,
        $authenticationURL);

$developerKey = 'DEVELOPER KEY'; /* https://code.google.com/apis/youtube/dashboard */
$applicationId = 'Video uploader v1';
$clientId = 'My video upload client - v1';

$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource('C:\Users\Public\Videos\Sample Videos\\Wildlife.wmv');
$filesource->setContentType('video/quicktime');
$filesource->setSlug('Wildlife.wmv');
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
// The category must be a valid YouTube category!
$myVideoEntry->setVideoCategory('Autos');
// Set keywords. Please note that this must be a comma-separated string
// and that individual keywords cannot contain whitespace
$myVideoEntry->SetVideoTags('personal');
// set some developer tags -- this is optional
// (see Searching by Developer Tags for more details)
$myVideoEntry->setVideoDeveloperTags(array('mydevtag', 'anotherdevtag'));

// upload URI for the currently authenticated user
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
// try to upload the video, catching a Zend_Gdata_App_HttpException,
// if available, or just a regular Zend_Gdata_App_Exception otherwise
try {
    $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
    echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
    echo $e->getMessage();
}
}
?>

Direct post integration eway

Create a eWay account. go: http://www.eway.com.au/developers/partners/become-a-partner.html

Post data as:

<form action="https://www.eway.com.au/gateway/payment.asp" method="post" name="formEWay">
<input type="hidden" name="ewayCustomerID" value=""/>
<input type="hidden" name="ewayTotalAmount" value=""/>
<input type="hidden" name="ewayCustomerFirstName" value=""/>
<input type="hidden" name="ewayCustomerLastName" value=""/>
<input type="hidden" name="ewayCustomerEmail" value=""/>
<input type="hidden" name="ewayCustomerAddress" value=""/>
<input type="hidden" name="ewayCustomerPostcode" value=""/>
<input type="hidden" name="ewayCustomerInvoiceDescription" value="Purchase Order - 10"/>
<input type="hidden" name="ewayCustomerInvoiceRef" value=""/>
<input type="hidden" name="eWAYURL" value="http://dom.com/ewayreturn.php"/>
<input type="hidden" name="eWAYSiteTitle" value="<?php echo $_SERVER["SERVER_NAME"] ?>"/>
<input type="hidden" name="eWAYAutoRedirect" value="1"/>
<input type="hidden" name="eWAYTrxnNumber" value=""/>
<input type="submit" value="Process Secure Credit Card Transaction using eWay"/>
</form>

After return from eway, try the following.
if(isset($_POST['ewayTrxnReference']) && isset($_POST['ewayTrxnStatus']) && isset($_POST['ewayTrxnNumber'])) {
    $orderStatus = "Open";
    $pGateResult = "false";
    $txn_id = $_POST['ewayTrxnReference'];
    $result = $_POST['ewayTrxnStatus'];
    $order_number = $_POST['ewayTrxnNumber'];
    $returnAmount = 0;
    if(isset($_POST["eWAYReturnAmount"])) {
        $returnAmount = $this->getValueReturnedFromeWay($_POST["eWAYReturnAmount"]);
    }
    if (!empty($result) && strcmp('True', trim($result)) == 0) {
         $pGateResult = "true";
         $orderStatus = "Paid";
    }
}