Skip to content

Instantly share code, notes, and snippets.

@jb41
Created March 30, 2017 20:43
Show Gist options
  • Save jb41/a22853dced476518b067eda01c35cb2a to your computer and use it in GitHub Desktop.
Save jb41/a22853dced476518b067eda01c35cb2a to your computer and use it in GitHub Desktop.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<form id="form">
<input type="text" name="name">
<input type="text" name="score">
<button type="submit">submit</button>
</form>
<script>
// jQuery snippet for changing HTML form into JSON
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) { o[this.name] = [o[this.name]]; }
o[this.name].push(this.value || '');
} else { o[this.name] = this.value || ''; }
});
return o;
};
})(jQuery);
$('#form').submit(function(e) {
// prevent default submiting form
e.preventDefault();
// serialize data to JSON
var data = $('#form').serializeFormJSON();
$.ajax({
url: 'https://sheetsu.com/apis/v1.0/020b2c0f',
data: data,
dataType: 'json',
type: 'POST',
// place for handling successful response
// showing (redirecting to) something like /thanks.html
// page could be a good idea
success: function(data) {
window.location.href = 'thank_you.html';
},
// handling error response
error: function(data) {
console.log(data);
}
});
return false;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment