serialize form data code example
Example 1: jquery serialize
var datastring = $("#contactForm").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
Example 2: jquery form serialize object
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$(this).serializeObject().done(function(o){
if(window.console) console.log(o);
var j = JSON.stringify(o);
alert(j);
//window.open("data:image/png;base64," + o.userfile.data);
});
});
});
Example 3: get serialize data javascript
// HTML
<form id="myForm" name="myForm">
<div>
<label for="username">Enter name:</label>
<input type="text" id="username" name="username">
</div>
<button type="button" onclick="clickMe()">Click</button>
</form>
// JS
function clickMe(){
let myForm = document.getElementById('myForm');
let formData = new FormData(myForm);
console.log(formData.get('username'));
}