Serialize html form to JSON without using JQuery
Transform user input from HTML form fields to JSON
jQuery makes things a lot easir when working with DOM. So many thing there out of the b and you do not need to worry about browsr compatibility.
Browser compatibility used to be a big deal few years back, but not it all comes to almost one engine which is WebKit.
In multimedia advertising on web using jQuery might be not such a good idea. When you do not need a robust behaviour and you tend to have less HTTP requests on your page load, you might re-thing about using jQueryor any other JavaScript framework. In this cse you need to go back to good old, plain JavaScript where there not so many out of the box stuff.
One thing that you will miss is serializing to JSON and using it in AJAX calls. So let's start with the code.
First we transform the form in an array by loping through input fields for form by fetching them by tag name:
function serializeArray(form) { var objects = []; if (typeof form == 'object' && form.nodeName.toLowerCase() == "form") { var fields = form.getElementsByTagName("input"); for(var i=0;i<fields.length;i++){ objects[objects.length] = { name: fields[i].getAttribute("name"), value: fields[i].getAttribute("value") }; } } return objects; }
No that we did heavy lifting, we can just serilaize it by using simply JSON.Stringify(object) function to get JSON string from object instance:
var dataObject = serializeArray(document.getElementsByTagName('form')[0]); var jsonData = JSON.stringify(dataObject);
Now when we have JSON string data we can easity use standard JavaScript objects to make an ajax call without using of any third party library or JavaSvript framework.
function ajaxPost(url, data, callback) { var xmlhttp = new XMLHttpRequest(); if (callback != null && typeof callback !== 'undefined' && typeof callback === 'function') xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { callback(this.responseText); } }; xmlhttp.open("POST", url, true); xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.send(data); }
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article