Search code examples
javascriptjqueryform-data

Retrieve and append array of input elements with keys to FormData


Supposing I have the following HTML input elements:

<input type="text" name="textinput[300]">
<input type="text" name="textinput[450]">
<input type="text" name="textinput[248]">

I'd like to retrieve the values of those fields to append them to a FormData object in order to send them to the server-side via Ajax. The keys within each array element is vital as it denotes a unique ID associated with each input field. The reason why I have the text field names set up as an array with unique keys is because I have the server-side code set up in the following manner:

<?php
if(isset($_POST['textinput'])){
    $IDs = array_keys($_POST['textinput']);

    foreach($IDs as $index => $ID){

        $field_value = $_POST["textinput"][$ID]);

        $query = "UPDATE `tablename` SET fieldname = $field_value WHERE `ID` = $ID";

        try{
            $stmt = $db->prepare($query);
            $result = $stmt->execute();
        }
        catch(PDOException $ex){
            die("UPDATE Failed ".$ex->getMessage());
        }

    }
}
?>

The following JS doesn't work for me, and apparently there's a lot more to this than just retrieving the input field, appending that to a Formdata object and sending it to the server side via ajax for processing:

<script>
        var textinput = document.getElementsByName('textinput');

        var data = new FormData();

        data.append('textinput[]', textinput);

        $.ajax({
            type: "POST",                
            url: "ajax-processing.php",
            processData: false,
            contentType: false,
            cache: false,
            data: data,
            success: function(data) {
                alert("Success!!!");
            },
            error: function(xhr, textStatus, errorThrown) {
                alert('Failed to save data');
            }
        });
}
</script>

Solution

  • Try changing

    var textinput = document.getElementsByName('textinput');
    var data = new FormData();
    data.append('textinput[]', textinput);
    

    To

    var data = new FormData();
    var textinputs = document.querySelectorAll('input[name*=textinp‌​ut]');
    for( var i = 0; i < textinputs.length; i++ )
        data.append(textinputs[i].name, textinputs[i].value);