kstratis kstratis -4 years ago 253
HTML Question

How to send a JSON object using html form data

So I've got this HTML form:

<html>
<head><title>test</title></head>
<body>
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>

<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>

<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
</html>


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?

UPDATE:
I've gone as far as this but it doesn't seem to work:

<script type="text/javascript">
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));


What am I doing wrong?

Answer Source

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.

$.ajax({
  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download