title: Passing javascript variable to servlet
body: <p>How can I pass a var from javascript to a servlet. Yes I know you can use getParameter on the servlet side, but I first need to do some javascript stuff then from there it need to pass that new variable to servlet.</p>
  
  <p>See my Javascript example:</p>
  
  <pre><code>function openBrWindowAndSubmit() { 
  
    var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
    alert(textBodyValue); //returns empty
    document.forms[0].submit();
  
    var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
    alert(textBodyValue); //works
  
  }
  </code></pre>
  
  <p>As you can see in above example the first "alert" block returns empty, but the second one returns the correct encoded value because the document.forms[0].submit is already called. So is there a way I can get the second variable "textBodyValue" (which is outside of document.forms[0].submit) to the servlet? I'm calling this at the servlet side:</p>
  
  <pre><code>String test = req.getParameter("textBody"); 
  </code></pre>
  
  <p>Here's the JSP inside a form tag which calls the function on click:</p>
  
  <pre><code> &lt;textarea id="textBody" name="textBody"&gt;&lt;/textarea&gt;        
   &lt;input type="button" onClick="openBrWindowAndSubmit();" value="Click Here to Preview Email"&gt;
  </code></pre>
  
  <p>Is there any workaround to this problem?</p>
  
  <p>I've been trying to change the javascript function to:</p>
  
  <pre><code>function openBrWindowAndSubmit() { //v2.0
  
    document.forms[0].target = "_blank";
    document.getElementById("action").value = "view_template";
    var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
    alert(textBodyValue);
    document.forms[0].submit();
  
    var textBodyValue = encodeURIComponent(document.getElementById("textBody").value);
    alert(textBodyValue);
  
    $.ajax({
        url: 'http://localhost:8080/restricted/comm/Email',
        data: textBodyValue,
      //  processData: false,
      //  contentType: false,
        type: 'POST',
        success: function(data){
          alert(data);
        }
      }); 
  }
  </code></pre>
  
  <p>Can this work? i'm getting an undefined error when reaching the $ajax tag?</p>