Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract HTML form data with javascript?

I need to extract data from an HTML form with javascript(+Mootools) in the same kind of nested object format that PHP would see it when the form is posted.

Am I just bad at googling or is there really no native nor a well-known way to achieve this? I see many others have asked the same question in different forums but so far all have accepted solutions like jQuery serializeArray and such.

I tried out serializeArray with jsFiddle http://jsfiddle.net/7quxe/ and the results were disappointing.

I've previously written a script for this myself and it worked quite well except it had some problems when the form had overlapping mixed key type fields (<input name="foo[bar]" value="1"> and <input name="foo[]" value="2". I've already started working on a better version but as I found myself starting over again and again, I thought to myself: There are lots of great js libraries out there that aim to solve many basic everyday problems. Can it really be that wanting to extract data from a form in a properly formatted object is not that common?

Here is an example of what I'm attempting:

<form method="post" action="/">
    <input name="test" value="test">
    <input name="nested[a]" value="a">
    <input name="nested[b]" value="b">
    <input name="nested[c]" value="c">
    <input name="arraytest[]" value="foo">
    <input name="arraytest[]" value="foo">
    <input name="arraytest[]" value="foo">
</form>

Here's how PHP would see this:

$_POST = array(
    'test' => 'test',
    'nested' => array(
        'a' => 'a',
        'b' => 'b',
        'c' => 'c',
    ),
    'arraytest' => array(
        0 => 'foo1',
        1 => 'foo2',
        2 => 'foo3'
    )
)

and this is what I'd like to get in js:

{
    test : 'test',
    nested : {
        a : 'a',
        b : 'b',
        c : 'c'
    },
    arraytest : {       // This could also be an array ['foo1','foo2','foo3']
        0 : 'foo1',
        1 : 'foo2',
        2 : 'foo3'
    }
}
like image 378
jpeltoniemi Avatar asked Feb 05 '26 08:02

jpeltoniemi


1 Answers

FormData data= new FormData();

Data consists of your all form data If you want specifically then you need to use

data.get("fieldName");
like image 189
Manjunath H Avatar answered Feb 07 '26 20:02

Manjunath H