VIEW DEMO
Utilizing the process of serializing, we are able to store input from an HTML form into JSON output.
<script type="text/javascript>
$(document).ready(function() {
$("#submitBtn").click(function(e){
var jsonData = {};
var formData = $("#myForm").serializeArray();
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax(
{
url : "process.php",
type: "POST",
data : jsonData,
});
e.preventDefault();
});
});
</script>
HTML CODE
<div id="header">
Sending Form Data as JSON
</div>
<form id="myForm" type="post">
<fieldset>
<legend>Ajax Form Submission </legend>
<p>Share your feedback with us by filling out the form below</p>
<div class="elements">
<label for="name">Name :</label>
<input required="required" type="text" value="John Doe" name="fname" size="20" />
</div>
<div class="elements">
<label for="Age">Age :</label>
<input required="required" type="number" value="25" id="age" name="age" size="10" />
</div>
<div class="elements">
<label for="pro"> Profession :</label>
<select name="pro">
<option value="Student">Student</option>
<option value="Engineer" selected="selected">Engineer</option>
</select>
</div>
<div class="elements">
<label for="Gender">Gender: </label>
<input type="radio" name="gender" value="Male" checked="checked" id="r1"> Male
<input type="radio" name="gender" value="Female" id="r2"> Female
</div>
<div class="elements">
<label for="hobby">Hobby :</label>
<input type="checkbox" name="hobby[]" value="Music" id="ch1" checked="checked"> Music
<input type="checkbox" name="hobby[]" value="Reading" id="ch2"> Reading
</div>
<div class="submit">
<input type="submit" id="submitBtn" name="submitBtn" class="btn" value="Submit" />
</div>
<span class="elements">Press "Ctrl + Shift + J" to view sent JSON in console: <span>
</fieldset>
</form>