简体   繁体   中英

serializeArray in a different way (from PHP foreach)

I want to POST via AJAX my form:

<form id="form_export">
<?php
foreach( $visitors as $k => $v )
{
    ?>
     <input type="hidden" name="<?php echo $k ?>" value="<?php echo htmlspecialchars( $v ) ?>">
    <?php
}
?>
</form>

Here is my AJAX:

$('#form_export').submit(function(e)
{
    e.preventDefault();


    var visitors = $(this).serializeArray();


    $.ajax({
        type      : 'POST',
        url       : '/ajax/ajax-export.php',
        data      : {visitors:visitors},
        beforeSend: function()
        {
            $('.preloader').css('display', 'block');
        },
        success   : function(resp)
        {
            $('.preloader').css('display', 'none');
            $('.message').html(resp);
        }
    })
})

The problem is, when i'm posting via AJAX i'm using .serializeArray() and the result is like this:

[visitors] => Array
    (
        [0] => Array
            (
                [name] => jumps
                [value] => bonding
            )

        [1] => Array
            (
                [name] => name
                [value] => SomeName
            )

        [2] => Array
            (
                [name] => surname
                [value] => SomeSurname
            )

        [3] => Array
            (
                [name] => firm
                [value] => SomeFirm
            )
        ...
    )

I tried plugin serializeForm.js and the format is almost ok but it gives me only last visitor (not all of them):

   [visitors] => Array
    (
        [jumps] => bonding
        [name] => SomeName
        [surname] => SomeSurname
        [firm] => SomeFirm
        ...
    )
    // END

Expected result should be like this:

   [visitors] => Array
   (
        [0] => Array
        (
            [jumps] => bonding, 
            [name] => SomeName,
            [surname] => SomeSurname,
            [firm] => SomeFirm,
            ...
        )
        [1] => Array
        (
            [jumps] => bonding,
            [name] => SomeSecondName,
            [surname] => SomeSecondSurname,
            ...
         )
         ...
   )

The number of columns may vary depending on the user's preferences. (I need to create table from this data this is why i want that data format).

Try this package: jQuery Serialize Object

It's really easy to use:

$(this).serializeJSON(); // to get the form as a JS object

Afterwards in PHP you can use json_decode with second parameter true to get your data as array in the way you want it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM