Logan West
Logan West

Reputation: 45

Sending an Unknown Amount of Ajax Data

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 updates the database accordingly.

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

Note: using print_r($_POST) I get the following:

?submit=Submit+Changes&price%5B%5D%3B+%3F>=5612&id%5B%5D=6&p‌​rice%5B%5D%3B+%3F>=2‌​5&id%5B%5D=5&price%5‌​B%5D%3B+%3F>=52&id%5‌​B%5D=3&price%5B%5D%3‌​B+%3F>=&id%5B%5D=2&p‌​rice%5B%5D%3B+%3F>=&‌​id%5B%5D=8

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {

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

        e.preventDefault();

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

//Multiple form elements generated depending on how many prices exist in database
<form>
    <input name="submit" type="submit" value="Submit Changes" />
    <table>
        <tbody> 
        <?php 
        $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++;?>
            </tr>
        <?php
        }?>
        </tbody>
    </table>
</form>

//price-update.php

<?php

    if($_POST) {

        //Uses SSL connection with mysqli
        require_once('connection.php');

        $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);
        }

    }

?>

Upvotes: 1

Views: 129

Answers (3)

bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

I belive the main issue is in your html:

<td><input type="number" name ="price[]; ?>" 
class="price-update" value="" min="1" max="999999999" /></td> 

Looking at above we can say that name is set to to name="price[]; ?"

The thing you want is to change name="price[] ;?>" to name="price[]"

Note1 Look into prepared statements / sql injections

Note2 Look into sql transactions

Upvotes: 0

Gonras Karols
Gonras Karols

Reputation: 1190

Following Dygnus's answer - If you still want to keep your data serialized, then you could do something like this to achieve your goal:

$query_arr = array(); $parsed_post = parse_str($_POST['data'], $query_arr);

and then loop through your foreach loop with $parsed_post.

Upvotes: 0

Dygnus
Dygnus

Reputation: 641

Serializing the data makes it a string (that's what actually is being sent). In order to send your form with content-type 'form-data/multipart', you'll have to pass a FormData and set the object for the data property:

$.ajax({
    type: 'post',
    url: '/price-update.php',
    data: new FormData($('form')[0]),
    success: function () {
        alert('Data was submitted');
    }
});

It's not necessary to specify the content type since the ajax() method of jQuery defaults to application/x-www-form-urlencoded.

Upvotes: 1

Related Questions