Skip to content

Instantly share code, notes, and snippets.

@phpdave
Last active August 29, 2015 14:26
Show Gist options
  • Save phpdave/266fe3cc50f447b6e6cb to your computer and use it in GitHub Desktop.
Save phpdave/266fe3cc50f447b6e6cb to your computer and use it in GitHub Desktop.
Takes the form data from HTML, adds some extra data, then encodes into JSON and request is sent to the server
<form id="myform">
<input id="CustomerName" name="CustomerName" type="text" />
<input id="Phone" name="Phone" type="text" />
...
</form>
<script type="text/javascript">
//Pull in all the data from the HTML form called myform
var postData = $("#myform").serializeObject();
//Add extra data to tell the server what im doing
postData.push({name:'action', value:"create"});
postData.push({name:'model', value:"customer"});
//Send it off to the server
$.post("../endpoint.php",
postData,
function(response)
{
if (response.status == true)
{
alert("Account created");
}
else
{
alert("An error occured");
}
}, "json");
$.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;
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment