15

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/

Andrea Rastelli
  • 617
  • 2
  • 11
  • 26
  • could you post the markup you're using? Please, set up an example fiddle – Fabrizio Calderan Apr 26 '12 at 13:34
  • If you are not opposed to using json2.js you can use that, or alternately, get it and study how it serializes, and learn from that source. – Mark Schultheiss Apr 26 '12 at 13:34
  • Are you reluctant to use any library at all? – Dave Hogan Apr 26 '12 at 13:35
  • 3
    A better way to learn is to look at the jquery source code. http://james.padolsey.com/jquery/#v=git&fn=serialize – codef0rmer Apr 26 '12 at 13:36
  • 1
    @F.Calderan this is my code: http://jsfiddle.net/XGD4X/ – Andrea Rastelli Apr 26 '12 at 13:43
  • @DaveHogan Yes, i whant to learn how jQuery (and others) works.. – Andrea Rastelli Apr 26 '12 at 13:44
  • @codef0rmer cool link! But the source is based (of course) on jQuery core.. and I actually don't need all jQuery's complexity :( – Andrea Rastelli Apr 26 '12 at 13:47
  • @AndreaRastelli: I think you should spend some time to understand that which will give you an idea when you go to implement your own solution. – codef0rmer Apr 26 '12 at 13:50
  • @codef0rmer Well.. what I know about javascript should be enough.. for example, I know that if I use somethink like: document.getElementById('form').elements I have an array of all elements inside the form, but what i don't know is how to convert all this array items into a JSON object – Andrea Rastelli Apr 26 '12 at 13:54
  • In that case, can not you just fetch all the elements exist into your form tag and put them into an array and then convert it into json. Is that what you trying to do? – codef0rmer Apr 26 '12 at 14:00
  • @codef0rmer mmh.. I think so. How I supposed to convert an array into a JSON object? And this array must have a particular key/value structure? – Andrea Rastelli Apr 26 '12 at 14:05

2 Answers2

2

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.

Jeff
  • 36
  • 3
  • So, basically, what I need to do is build some dataObj array to store my values (like dataObj[0].prod_name and dataObj[0].prod_num) and convert the entire array in a JSON string using JSON.stringify.. Am I right? Or I miss something? – Andrea Rastelli Apr 27 '12 at 09:08
  • As I understand it, JSON is mostly just the object literal javascript syntax, and the stringify method just strips away an objects methods (for safety) and leaves only the data. For a simple program you could just declare an empty object, add the data to it, stringify, and post. Use an Array if that makes sense for your data, or just an object. After breakfast I will adjust my post to show a more generic solution. Are you also interested in seeing my makeAjaxPost() function? – Jeff Apr 27 '12 at 12:24
  • Thanks for your time :D. About your makeAjaxPost function.. well.. I'm always interested. Now I make some tests with your suggestions. – Andrea Rastelli Apr 27 '12 at 13:43
  • Time well spent, as it clarifies my thinking on this topic. Might be best to see how far you get on your own from here. I will add part of my JDK module tomorrow, after I clean up the documentation. – Jeff Apr 27 '12 at 15:32
  • I looked over your code again, and I have some questions. Consider each row in your table as a data object, something like {name: 'widget', numA: '15', numB: '87'}, would you call this object a Product, or is there a better name? What is the difference between the number fields? Next consider a list of these objects something like {list: anArrayofProducts[...]}, how would you name this list? Have you considered using separate markup for each of these objects, a form to create a 'Product', which is added to the 'List', and a table to display the 'List'? – Jeff Apr 28 '12 at 12:00
  • mmh.. this is my field functionality: first field is the name of the product; second field is the slider (chrome only) for the quantity of the products; third field is the number field for the exact quantity of the product (i know, it seems a duplicate input but in my mind this second number input is for refinement and the first is for large step increments). My array of object (based on your example) is a container for each row in the table. – Andrea Rastelli Apr 28 '12 at 17:37
  • So the Product has only name and quantity, but quantity has 2 inputs on the page? aProduct = {name: "widget", quantity: "87"} Is your Container object a SalesHistory, a listOfDailyProduction, an Order, or something else? – Jeff Apr 28 '12 at 19:09
  • Just a test to improve my skills in JavaScript and PHP. With this table what I whant to do is to generate a Pie chart dinamically with Ajax. That's all. – Andrea Rastelli Apr 28 '12 at 20:47
1

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.

jholster
  • 5,066
  • 1
  • 27
  • 20