title: How to send a JSON object using html form data
body: <p>So I've got this HTML form:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;&lt;title&gt;test&lt;/title&gt;&lt;/head&gt;
  &lt;body&gt;
      &lt;form action="myurl" method="POST" name="myForm"&gt;
          &lt;p&gt;&lt;label for="first_name"&gt;First Name:&lt;/label&gt;
          &lt;input type="text" name="first_name" id="fname"&gt;&lt;/p&gt;
  
          &lt;p&gt;&lt;label for="last_name"&gt;Last Name:&lt;/label&gt;
          &lt;input type="text" name="last_name" id="lname"&gt;&lt;/p&gt;
  
          &lt;input value="Submit" type="submit" onclick="submitform()"&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Which would be the easiest way to send this form's data as a JSON object to my server when a user clicks on submit?</p>
  
  <p>UPDATE: 
  I've gone as far as this but it doesn't seem to work:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      function submitform(){
          alert("Sending Json");
          var xhr = new XMLHttpRequest();
          xhr.open(form.method, form.action, true);
          xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
          var j = {
              "first_name":"binchen",
              "last_name":"heris",
          };
          xhr.send(JSON.stringify(j));
  </code></pre>
  
  <p>What am I doing wrong?</p>