views:

83

answers:

3

I have an html:

First name: <input type='text' name='first_name' value='' /><br/>
Last name: <input type='text' name='last_name' value='' /><br/>
<input type='checkbox' name='category[]' value='Math' /> Math<br/>
<input type='checkbox' name='category[]' value='Science' /> Science<br/>
<input type='checkbox' name='category[]' value='History' /> History<br/>
etc.....

I want to send(using post method) the selected categories(category[]) via mootools ajax so that if I dump the $_POST variable in the server I will get something like:

array(1) {
   [category]=>
    array(2) {
    [0]=>
    string(4) "Math"
    [1]=>
    string(7) "History"
  }
}

What should be the javascript(mootools) code for it? Below is my partial code.

new Request.JSON({url: '/ajax_url',
            onSuccess: function(){
                alert('success');
            }
        }).post(???);

Note that I don't want to send first_name and last_name fields. I only want to send the category field which is an html array.

A: 

I would examine the source code of this function from the Prototype JS library to see how it works: line 100 at http://github.com/sstephenson/prototype/blob/master/src/dom/form.js#L100

It might require a little tweaking to accept the category[] format, but it's a start, or an inspiration.

Daniel Beardsley
+1  A: 

You simply need to serialize the fields:

var theForm = $('form-id');

new Request.JSON({url: '/ajax_url',
    onSuccess: function(){
        alert('success');
    }
}).post(theForm.toQueryString()); // this will create the GET-style query
Oskar Krawczyk
+1  A: 

here's one way to do it:

$("formid").addEvent("submit", function(e) {
    e.stop();
    var x = {};
    this.toQueryString().split('&').each(function(i) {
        var p = i.split('=');
        if (p[0].contains("[]")) {
            p[0] = p[0].replace("[]", "");
            if ($type(x[p[0]]) != "array")
                x[p[0]] = [];
            x[p[0]].push(p[1]);
        }
        else {
            x[p[0]] = p[1];
        }

    });
    // return a number of formats, depends on your backend:
    console.log(x, JSON.encode(x), $H(x).toQueryString());
});

this can output:

the object(x) or...

json {"first_name":"Dimitar","last_name":"Christoff","category":["Math","Science"]} or...

query string: first_name=Dimitar&last_name=Christoff&category[0]=Math&category[1]=Science

good luck. case: http://www.jsfiddle.net/dimitar/Wxx3b/1/

p.s. you are not meant to use the name[] as field names, this is really a shortcut / nice way for PHP to deal with things but its not for the clientside imo.

Dimitar Christoff