// there is no native support to create object from form, need this plugin function
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
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;
};
$(function() {
createForm();
$('form').submit(function() {
// JSO.stringify not supported in browsers older than IE8, FF3.?, need json2.js library for older support
var data = JSON.stringify($('form').serializeObject())
// now add ajax, see function below
//doAjax( data); uncomment to run
// utility just to display json this demo
$('#result').text(data);
return false;
});
});
// demo ajax function for REST
function doAjax(data) {
$.ajax({
url: 'REST_url',
data: data,
type: 'GET',
contentType: 'application/json',
dataType: 'jsonp', //I assume the REST is jsonp? if not use 'json'
success: function(returnData) {
// do something with return
},
error: function() {
alert('error')
}
});
}
// utility function to create form from array
function createForm() {
var fields = ["ListName", "FromName", "FromEmail", "Description", "FolderId"];
var html = [];
$.each(fields, function(i, item) {
html.push('<input name="' + item + '" type="text" value="' + item + '" /><br>');
});
$('form').prepend(html.join(''))
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.