Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize multidimensional form data into a JSON object-array to work with application/json

I am building a Laravel application. In the back-end, the $controller->wantsJson() method is TRUE if the content type of the request is application/json. So, to satisfy this, my jQuery AJAX call is this.

jQuery.ajax({
    type:        "POST",
    method:      "PUT",
    url:         $form.attr('action'),
    data:        $form.serialize(),
    dataType:    "json",
    contentType: "application/json; charset=utf-8"
})

This correctly triggers the wantsJson() response I need. The problem then is that jQuery cannot supply POST data as an application/json correctly. It tries to write it as a query string, which doesn't work for the PHP backend when it receives that content type.

To satisfy this, I need to stringify a JavaScript object-array into the data field.

JSON.stringify(dataObj)

So now the problem is, I don't have a concise way of turning a multidimensional form into an object-array. If I just try to convert the output of $.serializeArray(), I get this, which isn't able to be interpreted by the backend.

{
    'something' : 1,
    'field[foo]' : 2,
    'field[bar][]' : "a",
    'field[bar][]' : "b",
    'field[bar][]' : "c",
}

And that of course doesn't work. I need some sort of RegEx parser that can convert this form ...

<input name="something" value="1" />
<input name="field[foo]" value="2" />
<input name="field[bar][]" value="a" />
<input name="field[bar][]" value="b" />
<input name="field[bar][]" value="c" />

Into ...

{
    'something' : 1,
    'field'     : {
        'foo'   : 2,
        'bar'   : [
            'a',
            'b',
            'c',
        ]
    }
}

You'd expect something like this to exist already, but I can't find anything satisfactory.

like image 665
Josh Avatar asked Sep 21 '15 03:09

Josh


1 Answers

I had the same problem but this package did the trick: jQuery Serialize Object

It's easy to use, just call this on your form (after loading the script)

$('form#contact').serializeJSON(); // to get the form as a JS object
like image 109
mvpasarel Avatar answered Sep 25 '22 14:09

mvpasarel