Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I've gotten Ajax to work on simple forms, but when I try to generate multiple form elements in a loop I have trouble unpacking all that data and using it to update my database. Anyone have any input on how I could achieve this based on my code below? Basically, each line item has the potential to have its price updated. When the user clicks the submit button, it calls a function to Ajax, which should pass all the form data to price-update.php. There, it unpacks every $_POST and update the database accordingly.

Note: This code is reduced for visual ease. Some variables are used, but methods for initialization are not given.

Doing a print_r($_POST) test results in the following in the URL:


<script src=""></script>
$(function () {

    $('form').on('submit', function (e) {


            type: 'post',
            url: '/price-update.php',
            data: $('form').serialize(),
            success: function () {
                alert('Data was submitted');

//Multiple form elements generated depending on how many prices exist in database
    <input name="submit" type="submit" value="Submit Changes" />
        $n = 0;
        for ($z = 0; $z < count($names); $z++) { ?>
            <tr id = "row-<?php echo $z; ?>">
                <td><input type="number" name ="price[]; ?>" class="price-update" value="" min="1" max="999999999" /></td>
                <td><input type="hidden" name="id[]" class="price-id" value="<?php echo $id_array[$n]; ?>" /></td>
                <?php $n++;?>



    if($_POST) {

        //Uses SSL connection with mysqli

        $IDs = array();
        $Prices = array();

        foreach($_POST as $key => $value) {
            if (strstr($key, 'id'))
                $IDs[] = $value;
            if (strstr($key, 'price'))
                $Prices[] = $value;

        for($i = 0; $i < count($IDs); $i++) {
            $price_update = "UPDATE prices SET price='".$Prices[$i]."' WHERE id='".$IDs[$i]."'";
            $send_update = $instance->query($price_update);



What I have tried:

Many variations. Simple forms update database just fine - but generating form elements form a PHP loop seems to cause problems. I think my issue is with the flow control for the $_POST elements.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900