title: AJAX request doesn't work the first time but works thereafter
body: <p>I'm making a simple function as it is shown on w3schools official website. I'm trying to run a function of an AJAX request.</p>
  <p>I guess it's all working well except the fact that the code ONLY runs after it fails the first time. I mean, let's say you just came the first time to my website and you try to submit the first time, it just refreshes the page and nothing happens.</p>
  <p>As far as I'm aware I tried to debug using <code>alert</code> functions in each line to find if the request was really being made. I found that the <code>readyState</code> jumps from 1 to 4 the very first time the code runs (in every browser, different computers), but next time it will render readyState 1, 2, 3 and 4 and BANG it will work and submit.</p>
  <p><strong>Javascript function code</strong> (inside head tag)</p>
  <pre><code>function sendForm() {
          
      var criarRequest = new XMLHttpRequest();
      criarRequest.onreadystatechange = function() {  
          if (criarRequest.readyState == 4 &amp;&amp; criarRequest.status == 200) {
              document.getElementById(&quot;contacts&quot;).innerHTML = criarRequest.responseText;
          } 
      };
      //var loading  = document.getElementById(&quot;contacts&quot;).innerHTML = &quot;A enviar...&quot;;
      var inputEmail = document.getElementById(&quot;email&quot;).value;
      var inputMensagem = document.getElementById(&quot;mensagem&quot;).value;  
      criarRequest.open(&quot;POST&quot;, &quot;sendEmail.php&quot;, true);
      criarRequest.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
      criarRequest.send(&quot;email=&quot;+inputEmail+&quot;&amp;mensagem=&quot;+inputEmail);
  }
  </code></pre>
  <p><strong>HTML code form/inputs</strong></p>
  <pre><code>&lt;form&gt;
      &lt;input style=&quot;width:220px; height:39px&quot; type=&quot;text&quot; id=&quot;email&quot; placeholder=&quot;Email&quot; /&gt; 
      &lt;br  /&gt; &lt;br  /&gt;
      &lt;textarea style=&quot;width:220px; height:100px&quot; id=&quot;mensagem&quot; placeholder=&quot;Mensagem&quot;&gt;&lt;/textarea&gt;
      &lt;br  /&gt; &lt;br  /&gt;
      &lt;button id=&quot;enviar&quot; onclick=&quot;sendForm()&quot;&gt;Enviar&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>