Chris G.
Chris G.

Reputation: 3981

JQuery, serializing html array

I have HTML that looks like this:

<form id="kinodForm">
    <input type="text" name="element[5]" value="krispy kreme" />
    <input type="text" name="element[6]" value="in" />
    <input type="text" name="element[7]" value="n" />
    <input type="text" name="element[8]" value="out" />
    <input type="text" name="element[9]" value="drive" />
</form>

And some javascript that looks like this:

$(document).ready(function(){
    var kinod = $('#kinodForm').serializeArray();
    $.post('test.php', {form: kinod}, function(data){
        console.log(data);
    });
});

The PHP script that the ajax request is bound to is simple:

<?php print_r($_POST); ?>

The result of the post request is being logged to the console. It's outputting something like this:

[form] => Array ( 
    [0] => Array ( [name] => element[5] [value] => 'krispy kreme' ) 
    [1] => Array ( [name] => element[6] [value] => 'in' ) 
    [2] => Array ( [name] => element[7] [value] => 'n' ) 
    [3] => Array ( [name] => element[8] [value] => 'out' ) 
    [4] => Array ( [name] => element[9] [value] => 'drive' ) 
)

This output isn't perfect because I want to be able to do this in the PHP script above without regex:

<?php
    $form = $_POST['form'];
    foreach($form as $id => $value){
        echo 'element['.$id.'] -> '.$value.'<br>';
    }
?>

This code will obviously be using the values {0,1,2,3,4} for $id, when I want them to stay the same as defined in the HTML form. {5,6,7,8,9}

I feel like I shouldn't have to parse the html array id. Suggestions?

Upvotes: 0

Views: 979

Answers (2)

okyanet
okyanet

Reputation: 3146

Why not use .serialize() then explode by '&' to get your form data into an array you can then loop over?

Upvotes: 0

Ayman Safadi
Ayman Safadi

Reputation: 11552

Try this:

$.post('test.php', kinod, function(data){
    console.log(data);
});

Upvotes: 1

Related Questions