Form Serialize JavaScript (No Framework)

form serialize javascript (no framework)

The miniature from-serialize library doesn't rely on a framework. Other than something like that, you'll need to implement the serialization function yourself. (though at a weight of 1.2 kilobytes, why not use it?)

how to serialize a form without jQuery?

I am working on a similar problem, and I agree that it is worthwhile to learn how to program first without using a framework. I am using a data object (BP.reading) to hold the information, in my case a blood pressure reading. Then the JSON.stringify(dataObj) dose the work for you.

Here is the handler for the 'save' button click, which is a method on the dataObj. Note I am using a form instead of a table to input data, but the same idea should apply.

update: function () {
var arr = document.getElementById("BP_input_form").firstChild.elements,
request = JDK.makeAjaxPost(); // simple cross-browser httpxmlrequest with post headings preset

// gather the data and store in this data obj
this.name = arr[0].value.trim();
...
this.systolic = arr[3].value;
this.diastolic = arr[4].value;

// still testing so just put server message on page
request.callback = function (text) {
msgDiv.innerHTML += 'server said ' + text;
};
//
request.call("BP_update_server.php", JSON.stringify(this));
}

I hope this is helpful

* edit to show generic version *

In my program, I am using objects to send, receive, display, and input the same kind of data, so I already have objects ready. For a quicker solution you can just use a empty object and add the data to it. If the data is a set of the same type of data then just use an array. However, with a object you have useful names on the server side. Here is a more generic version untested, but passed jslint.

function postUsingJSON() {
// collect elements that hold data on the page, here I have an array
var elms = document.getElementById('parent_id').elements,
// create a post request object
// JDK is a namespace I use for helper function I intend to use in other
// programs or that i use over and over
// makeAjaxPost returns a request object with post header prefilled
req = JDK.makeAjaxPost(),
// create object to hold the data, or use one you have already
dataObj = {}, // empty object or use array dataArray = []
n = elms.length - 1; // last field in form

// next add the data to the object, trim whitespace
// use meaningful names here to make it easy on the server side
dataObj.dataFromField0 = elms[0].value.trim(); // dataArray[0] =
// ....
dataObj.dataFromFieldn = elms[n].value;

// define a callback method on post to use the server response
req.callback = function (text) {
// ...
};

// JDK.makeAjaxPost.call(ULR, data)
req.call('handle_post_on_server.php', JSON.stringify(dataObj));
}

Good Luck.

HTML/Javascript Form How do I serialize li data when submitted?

JavaScript by nature cannot post dynamic form elements through a typical HTML 'submit' button. It would be fairly straightforward with jQuery, but you say you cannot use that. Also, your HTML structure makes dealing with form submission through raw JavaScript rather clunky, as you can't edit it to attach a function to the form submission (nor change the HTML).

You also need to serialize the form before submission, which is clunky without jQuery. There's plenty of libraries to do that, but you may need a particular one based on your code structure. Plenty of examples on how to do that can be found here.

// Sample serialization function structure
function serialize(form) {
// Serialize
}

You would then need to create a JavaScript element from the form, attach an event listener manually, prevent the form submission, serialize the data, and re-submit manually.

const element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
serialize(element);
element.submit();
});

A complex process, and you may want to look into an alternative approach to the process as a whole. However, I hope this is able to solve your problem :)

Using JavaScript to submit form data with HTTP request same like ajax form serialize

You can use FormData, like this:

let data = new FormData(document.querySelector('form'));

And then:

let request = new XMLHttpRequest();
request.open("POST", "url");
request.send(data);

More info: FormData API

I hope it helps you

How Do I Post A Form Without Redirecting Using Raw Javascript?

Unless resorting to hacks like posting to a dummy target, AJAX is the way to go.

This works:

    const form =  document.querySelector("#message-form");
form.addEventListener("submit", event => {
event.preventDefault()

let status = "";
const data = new FormData(form);
const req = new XMLHttpRequest();
try{
req.open("POST", '/send-message');
req.send(data);
status = "success";
}
catch{
status = "failure";
}
notifyuser(status);
});

Serialize complex form to JSON object using jQuery

Try this code I wrote for you... Works fine for me, just using your data result. You can work on it and make a simple jQuery plugin...

The sample need JSON.stringify to work fully.

var d = {
'name': 'name value',
'phone[0][type]': 'cell',
'phone[0][number]': '000',
'phone[1][type]': 'home',
'phone[1][number]': '111',
};

$(document).ready(function(){

arrangeJson(d);
alert(JSON.stringify(d));
});

function arrangeJson(data){
var initMatch = /^([a-z0-9]+?)\[/i;
var first = /^\[[a-z0-9]+?\]/i;
var isNumber = /^[0-9]$/;
var bracers = /[\[\]]/g;
var splitter = /\]\[|\[|\]/g;

for(var key in data) {
if(initMatch.test(key)){
data[key.replace(initMatch,'[$1][')] = data[key];
}
else{
data[key.replace(/^(.+)$/,'[$1]')] = data[key];
}
delete data[key];
}

for (var key in data) {
processExpression(data, key, data[key]);
delete data[key];
}

function processExpression(dataNode, key, value){
var e = key.split(splitter);
if(e){
var e2 =[];
for (var i = 0; i < e.length; i++) {
if(e[i]!==''){e2.push(e[i]);}
}
e = e2;
if(e.length > 1){
var x = e[0];
var target = dataNode[x];
if(!target){
if(isNumber.test(e[1])){
dataNode[x] = [];
}
else{
dataNode[x] ={}
}
}
processExpression(dataNode[x], key.replace(first,''), value);
}
else if(e.length == 1){
dataNode[e[0]] = value;
}
else{
alert('This should not happen...');
}
}
}
}


Related Topics



Leave a reply



Submit