0

I'm trying to get together a basic example of how to use Google Closure to minify JS. I can't seem to get this to work at all.

I'm trying to follow these examples:

https://developers.google.com/closure/compiler/docs/gettingstarted_api http://closure-compiler.appspot.com/home

When working on API's and/or AJAX code, the first thing I try to is get the variables and values setup properly using just Advanced Rest Client Applications - a Chrome Extension. Whenever I send this data, though, I get an empty response (image below).

Trying to insert the same code into my PHP code, no matter what I send in the $postData variable, I get an empty (null) response.

PHP Code:

$postData =
    http_build_query(
    [
        'output_info' => 'compiled_code', 
        'output_format' => 'text', 
        'compilation_level' => 'SIMPLE_OPTIMIZATIONS', 
        'js_code' => urlencode("function hello(name) {       // Greets the user       alert('Hello, ' + name);     }     hello('New user');")
    ]
);

$ret = $this->ci->curl->simple_post(
    $url,
    $postData,
    $options
);

var_dump($ret);
die();

Response:

string ' ' (length=1)

I'm 99% confident that I'm missing something to use the Closure API like a key or something, but I have no idea how to proceed.

Closure Issue

VPel
  • 413
  • 5
  • 12
  • I've narrowed it down to the urlencode function not encoding the script like the Closure API is expecting. When I run the example Closure API and use jQuery to serialize the form, I get this for the JavaScript encoded: ++++function+hello(name)+%7B%0D%0A++++++%2F%2F+Greets+the+user%0D%0A++++++alert('Hello%2C+'+%2B+name)%3B%0D%0A++++%7D%0D%0A++++hello('New+user')%3B%0D%0A++++ BUT when I run the same string through PHP encode, I get this: function+hello%28name%29+%7B+++++++%2F%2F+Greets+the+user+++++++alert%28%27Hello%2C+%27+%2B+name%29%3B+++++%7D+++++hello%28%27New+user%27%29%3B – VPel May 30 '14 at 14:12

1 Answers1

1

After many, many, many attempts, I found that if I used rawurlencode() instead of urlencode(), it works. Here's the final function.

    // use google closure to get compiled JS
    $encoded = rawurlencode($js);

    $postData =
            'output_info=compiled_code&' . 
            'output_format=text&' .
            'compilation_level=WHITESPACE_ONLY&' .
            'js_code=' . $encoded
    ;
    $options = [];

    $call = curl_init();
    curl_setopt_array(
             $call, 
             array(
                 CURLOPT_URL => 'http://closure-compiler.appspot.com/compile',
                 CURLOPT_POST => 1,
                 CURLOPT_POSTFIELDS => $postData,
                 CURLOPT_RETURNTRANSFER => 1,
                 CURLOPT_HEADER => 0,
                 CURLOPT_FOLLOWLOCATION => 0
              )
    );
    $jscomp = curl_exec($call);

    return $jscomp;
VPel
  • 413
  • 5
  • 12