Reputation: 14469
I'm attempting to access the Closure Compiler tool programmatically, but having issues both with PHP and JavaScript. Here is a quick and dirty PHP script I whipped up just to play around with the compilers' REST API:
<?php
if (!empty($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre><br />';
foreach ($_POST as $k => &$v) $v = urlencode($v);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
curl_setopt($ch, CURLOPT_URL, 'http://closure-compiler.appspot.com/compile');
echo curl_exec($ch);
} else {
echo "
<html>
<body>
<form action='' method='post'>
<p>Type JavaScript code to optimize here:</p>
<textarea name='js_code' cols='50' rows='5'>
function hello(name) {
// Greets the user
alert('Hello, ' + name);
}
hello('New user');
</textarea>
<input type='hidden' name='compilation_level' value='WHITESPACE_ONLY' />
<input type='hidden' name='output_format' value='json' />
<input type='hidden' name='output_info' value='compiled_code' />
<input type='hidden' name='warning_level' value='VERBOSE' />
<br /><br />
<input type='submit' value='Optimize' />
</form>
</body>
</html>";
}
The output I see is:
Array
(
[js_code] => function hello(name) {
// Greets the user
alert(\'Hello, \' + name);
}
hello(\'New user\');
[compilation_level] => WHITESPACE_ONLY
[output_format] => json
[output_info] => compiled_code
[warning_level] => VERBOSE
)
Error(13): No output information to produce, yet compilation was requested.
I thought, maybe there's a problem with my cURL options. So I tried JavaScript (via a jQuery.post() call). I "jQuerify"d a random Firefox window and ran the following code in the Firebug console:
$.post('http://closure-compiler.appspot.com/compile',
{
'js_code': "function hello(name) {/*Greets the user*/alert('Hello, ' + name);}",
'compilation_level': 'SIMPLE_OPTIMIZATIONS',
'output_format': 'text',
'output_info': 'compiled_code'
},
function(response) {
alert(response);
}
);
The "Net" panel shows a 403 error for this.
What am I missing?
Upvotes: 1
Views: 915
Reputation: 196177
Ajax (via jQuery or otherwise) will not work because of same-origin policy. (ajax requests are restricted in same domain, unless jsonp is expected as result)
Simply using your example to post the info, it works as seen in http://www.jsfiddle.net/RySLr/
So it must be what @German Rumm mentions..
Upvotes: 1
Reputation: 5832
According to API docs
The request must always have a Content-type header of application/x-www-form-urlencoded
Didn't see that in your code
Add
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
before curl_exec()
Upvotes: 5