Google Closure Compiler with ajax

by Faisal Khan Janjua

HTML

<form id="compileThis">
  <textarea name="js_code" id="tobeCompile">
    // this is empty text and needs compilation
    /* this is multiline text
    and second line starts here...
    */
    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="text">
  <input type="hidden" name="output_info" value="compiled_code">

  <input type="submit" value="Optimize" id="optimizeJS">
</form>
<textarea id="compiledText"></textarea>

<br><br><hr>
<p>example without AJAX</p>


<form method="POST" action="https://closure-compiler.appspot.com/compile">
  <textarea name="js_code" id="tobeCompile">
    // this is empty text and needs compilation
    /* this is multiline text
    and second line starts here...
    */
    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="text">
  <input type="hidden" name="output_info" value="compiled_code">

  <input type="submit" value="Optimize" id="optimizeJS">
</form>

CSS

body {
  background: #FFF;
}
pre {
  color:#FFF;
}
hr {
  clear:both;
}
textarea {
  width: 45%;
  float: left;
  min-height: 200px;
}
input {
  clear: both;
  float: left;
}
#compiledText {
  float: none;
  margin-left: 10px;
}

JavaScript

$(document).on('submit', '#compileThis', function(e){
  e.preventDefault();
  jQuery.ajax({
    type: "POST",
    url: 'https://closure-compiler.appspot.com/compile',
    data: $('#tobeCompile').val(),
    timeout: 3000,
    success: function (data){
      $('#compiledText').val(data);
    },
    error: function(){
      alert('TimeOut');
    }
  });
});

/* 
		// Above code is wrong and asked for correction on Stackoverflow
		// below solution is provided by stackoverflow community
    data: {
      "js_code": $("#tobeCompile").val(),
      "compilation_level": "WHITESPACE_ONLY",
      "output_format": "text",
      "output_info": "compiled_code"

    },
*/