Thursday, August 8, 2013

jQuery check a checkbox without firing a change event

You should suspend events before set the value and resume events after this. For example:
myCheckBox.suspendEvents(false); // Stop all events. 
//Be careful with it. Dont forget resume events!
myCheckBox.setValue(!myCheckBox.getValue()); // invert value
myCheckBox.resumeEvents(); // resume events

Wednesday, August 7, 2013

Refund transaction using php api using eWay account

/* Refund using eWay */
function refund_using_eway()
{
    $testUrl = "https://www.eway.com.au/gateway/xmltest/refund_test.asp";
    $liveUrl = "https://www.eway.com.au/gateway/xmlpaymentrefund.asp";

    $eWaySOAPActionURL = "https://www.eway.com.au/gateway/managedpayment";
    $eWayCustomerId = "87654321";
    $eWayTotalAmount = 100;
    $directXML = "<ewaygateway>" .
        "<ewayCustomerID>" . $eWayCustomerId . "</ewayCustomerID>" .
        "<ewayOriginalTrxnNumber>20488</ewayOriginalTrxnNumber>" .
        "<ewayTotalAmount>" . $eWayTotalAmount . "</ewayTotalAmount>" .
        "<ewayCardExpiryMonth>01</ewayCardExpiryMonth>" .
        "<ewayCardExpiryYear>2015</ewayCardExpiryYear>" .
        "<ewayOption1></ewayOption1>" .
        "<ewayOption2></ewayOption2>" .
        "<ewayOption3></ewayOption3>" .
        "<ewayRefundPassword>test123</ewayRefundPassword>" .
        "</ewaygateway>";

    $result = makeCurlCall(
        $testUrl, /* CURL URL */
        "POST", /* CURL CALL METHOD */
        array( /* CURL HEADERS */
            "Content-Type: text/xml; charset=utf-8",
            "Accept: text/xml",
            "Pragma: no-cache",
            "SOAPAction: " . $eWaySOAPActionURL,
            "Content_length: " . strlen(trim($directXML))
        ),
        null, /* CURL GET PARAMETERS */
        $directXML /* CURL POST PARAMETERS AS XML */
    );

    if ($result != null && isset($result["response"])) {
        $response = new SimpleXMLElement($result["response"]);
        $response = simpleXMLToArray($response);
        print_r2($response);
    }
    die("");
}

/* makeCurlCall */
function makeCurlCall($url, $method = "GET", $headers = null, $gets = null, $posts = null) {
    $ch = curl_init();
    if($gets != null)
    {
        $url.="?".(http_build_query($gets));
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    if($posts != null)
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    }
    if($method == "POST") {
        curl_setopt($ch, CURLOPT_POST, true);
    } else if($method == "PUT") {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    } else if($method == "HEAD") {
        curl_setopt($ch, CURLOPT_NOBODY, true);
    }
    if($headers != null && is_array($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    curl_close($ch);
    return array(
        "code" => $code,
        "response" => $response
    );
}

/* Response */
Array
(
    [ewayTrxnStatus] => Array
        (
            [__cdata] => False
        )

    [ewayTrxnNumber] => Array
        (
            [__cdata] =>
        )

    [ewayTrxnOption1] => Array
        (
            [__cdata] =>
        )

    [ewayTrxnOption2] => Array
        (
            [__cdata] =>
        )

    [ewayTrxnOption3] => Array
        (
            [__cdata] =>
        )

    [ewayAuthCode] => Array
        (
            [__cdata] =>
        )

    [ewayReturnAmount] => Array
        (
            [__cdata] => 100
        )

    [ewayTrxnError] => Array
        (
            [__cdata] => Error: Invalid Original Transaction Number. Your credit card has not been billed for this transaction.
        )

)

/* Dont worry about ewayTrxnError, when you refund live it will work */

Grails bean/service initialization dynamically to handle circular dependency

Suppose you have a service named OneService and another service named TwoService;
Now if you try to initiate TwoService in OneService and OneService in TwoService then you have some error regarding circular depency.

class OneService {
    def twoService;
}

class TwoService {
    def oneService;
}
To handle this you may need some trick.
First create a private static variable myTwoService and then initiate it when call it.

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA

class OneService {
    def ctx
    private static TwoService myTwoService;

    def getTwoService() {
        if(!ctx) {
            ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
        }
        if(!myTwoService) {
            myTwoService = ctx.getBean("twoService");
        }
        return myTwoService;
    }

    def someFunction = {
        def str = twoService.callSomeFunction();  
        /* it actually call getTwoService */
    }
}
And change you TwoService to call OneService such this way.

How do I get an instance of a Grails service programmatically

The Grails documentation describes a way to get a service when in a servlet. This might be useful, if you can obtain the same objects in your context:

ApplicationContext ctx = (ApplicationContext)ApplicationHolder.getApplication().getMainContext();
CountryServiceInt service = (CountryServiceInt) ctx.getBean("countryService");
String str = service.sayHello("Some String!");

Sunday, August 4, 2013

Image Data URIs with JavaScript

<img src="your_image.png" id="myimage" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>


You will need to create a canvas element with the correct dimensions and copy the image data with thedrawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.
It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.
function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL();

    return dataURL;
}
var myImage = document.getElementById('myimage');
var imageData = getbase64Image(myImage);
Return like something: "data:image/png;base64,BASE_64_IMAGE_DATA"; 

Image Data URIs with PHP

If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves a network request for each image, and if you're the paranoid type, can prevent exposure of directory paths. Since creating data URIs is incredibly easy, let me show you how to do it with PHP.

The PHP

Start by reading in the image using file_get_contents (or any other PHP method you'd like), then convert the image to base64 using base64_encode:
// A few settings
$image = 'cricci.jpg';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="',$src,'">';
With the image data in base64 format, the last step is placing that data within the data URI format, including the image's MIME type. This would make for a good function:
function getDataURI($image, $mime = '') {
	return 'data: '.(function_exists('mime_content_type') ? mime_content_type($image) : $mime).';base64,'.base64_encode(file_get_contents($image));
}
The thing to remember is that IE7 and lower don't support data URIs, so keep that in mind if you're considering switching from image paths to data URIs!

http://davidwalsh.name/data-uri-php 

Thursday, August 1, 2013

How to Run PHP Scripts in *.html or *.htm Files

One of the most common questions hitting our support inbox is how to get PHP working in *.html and *.htm files. With this blog we try to provide a practical guide for our users and thus kill two birds with one stone figuratively.

Question One: Does my web host support PHP?

At first you should try to find our whether PHP is supported by your webhost or not. If you already know that PHP works please continue to read at Question Two. If you don't know you could either ask your hosting company or you could just try it by following these steps:
First, create a file named "phptest.php". At this stage it is important to use the file extension ".php". Open the file in a simple text editor (for example the "Editor" in Windows) and write the following line:
<?php echo "hello world"; ?>
After saving the file please upload it to the root directory of your webspace. Open your browser and direct it to the file you just uploaded: "http://www.your-domain.com/phptest.php" (Needless to say, you should use your own domain here...)
It's the moment of truth now. What does the browser say? If you see the words "hello world" everything is fine, PHP is working. However, if you don't see these words please contact your hosting provider because PHP is not working (yet). Most hosting companies provide packages including PHP. So perhaps you just have to switch to another hosting plan.

Question Two: How to get PHP working in HTML files

If PHP is working there is only one step left to use PHP scripts in files with *.html or *.htm extensions as well. The magic word is ".htaccess". Please see the Wikipedia definition of .htaccess to learn more about it. According to Wikipedia it is "a directory-level configuration file that allows for decentralized management of web server configuration."
You can probably use such a .htaccess configuration file for your purpose. In our case you want the webserver to parse HTML files like PHP files.
First, create a blank text file and name it ".htaccess". You might ask yourself why the file name starts with a dot. On Unix-like systems this means it is a dot-file is a hidden file.
(Note: If your operating system does not allow file names starting with a dot just name the file "xyz.htaccess" temporarily. As soon as you have uploaded it to your webserver in a later step you can rename the file online to ".htaccess")
Next, open the file with a simple text editor like the "Editor" in MS Windows. Paste the following line into the file:
AddType application/x-httpd-php .html .htm
If this does not work, please remove the line above from your file and paste this alternative line into it, for PHP5:
AddType application/x-httpd-php5 .html .htm
Now upload the .htaccess file to the root directory of your webserver. Make sure that the name of the file is ".htaccess". Your webserver should now parse *.htm and *.html files like PHP files.
You can try if it works by creating a HTML-File like the following. Name it "php-in-html-test.htm", paste the following code into it and upload it to the root directory of your webserver:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
	<TITLE>Use PHP in HTML files</TITLE>
	</HEAD>
 
	<BODY>
		<h1>
		<?php echo "It works!"; ?>
		</h1>
	</BODY>
</HTML>
 
Try to open the file in your browser by typing in: http://www.your-domain.com/php-in-html-test.htm (once again, please replace your-domain.com by your own domain...)
If your browser shows the phrase "It works!" everything works fine and you can use PHP in .*html and *.htm files from now on. However, if not, please try to use the alternative line in the .htaccess file as we showed above. If is still does not work please contact your hosting provider.