Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize a form without jQuery? [duplicate]

For a lot of reasons (first of all: learning javascript), I need to serialize a form without jQuery, and send the resulting serialized data-structure to a php page with ajax. The serialized data must be in JSON format.

How can I do that?

--EDIT--

this is how my form looks like: http://jsfiddle.net/XGD4X/

like image 539
Andrea Rastelli Avatar asked Apr 26 '12 13:04

Andrea Rastelli


2 Answers

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.

like image 103
Jeff Avatar answered Sep 17 '22 14:09

Jeff


CoffeeScript implementation returning a GET query string:

serialize = (form) ->
  enabled = [].filter.call form.elements, (node) -> not node.disabled
  pairs = [].map.call enabled, (node) ->
    encoded = [node.name, node.value].map(encodeURIComponent)
    encoded.join '='
  pairs.join '&'

Or if you rather prefer a key-value map:

serialize = (form) ->
  data = {}
  for node in form.elements when not node.disabled and node.name
    data[node.name] = node.value
  data

I haven't looked at jQuery's implementation, so no 100% compatibility guaranteed.

like image 40
jholster Avatar answered Sep 18 '22 14:09

jholster