0

I've been trying to parse the $_POST data to retrieve a range of prices and id's encoded within. Can someone point me in the right direction, please? Here is what I have:

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

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

          //e.preventDefault();

          var form = $('form')[0];
          var formData = new FormData(form);

          $.ajax({
            url: '/price-update.php',
            data: formData,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function () {
              alert('form was submitted');
            }
          });

        });

      });
</script>

Example of the $_POST data sent:

?submit=Submit+Changes&price%5B%5D=11&id%5B%5D=6&price%5B%5D=22&id%5B%5D=5&price%5B%5D=33&id%5B%5D=3&price%5B%5D=44&id%5B%5D=2&price%5B%5D=55&id%5B%5D=8

<?php

//Part of my price-update.php file

    if($_POST) {

        $Values = array();
        parse_str($_POST, $Values);

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

    }

?>

I get the success message popup saying that form was submitted. But no values are changed within the database.

Logan West
  • 45
  • 6

1 Answers1

0

I've changed your code a bit and added part to php file which returns some values to the frontend so the example is complete.

html file:

<form id="form">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>

javascript file:

$(function () {

    $('#form').on('submit', function (e) {   // get element with id="form"

        e.preventDefault();  // prevent default form submission

        var form = $('form')[0];
        var formData = new FormData(form);

        $.ajax({
            url: '/price-update.php',
            data: formData,
            type: 'POST',
            contentType: false,
            processData: false,
            done: function (res) {
                console.log('res', res);
                alert('form was submitted');
            }
        });

    });

});

php file:

<?php

if($_POST['bar']) {

    $values = array();

    foreach ($_POST as $key => $value) {
       $values[$key] = $value;  // do something with values (for example put them to array)
    }

    echo json_encode($values);  // return those values to the frontend
}

You can look at the more detailed description here.

Community
  • 1
  • 1
boroboris
  • 1,548
  • 1
  • 19
  • 32