using javascript/jquery and ajax to set a php variable from select

79 views Asked by At

When a user is adding information to my form, I want them to chose an option from a select box #1 and I want to get that answer and set it to a variable in php. This variable will be used in a sql call to populate another select box #2. I want this to work with ajax so that the user doesn't have to press submit to have the select box #2 populate. I almost have a working code, this jquery/ajax request does do what I want (send the data to php to put in a variable so I can populate select box #2) but it breaks my form submission at the bottom of the page. The form won't submit unless I refresh the page and that defeats the whole purpose.

javascript

$(document).ready(function() {
    $( "#Mcage" ).change(function() {
        $( "#Mcage option:selected" ).each(function() {
            var malestr =$(this).text();
            $.ajax({
                url: 'addbcage.php',
                type: 'GET',
                data: { mval: malestr },
                    success: function(response) {
                        $('body').html(response);

                    },
                });
          });
    });
});

php used to set session variable

if (!empty($_GET['mval'])) {
    $_SESSION["m_cage"] = $_GET['mval'];
}
$m_cage = $_SESSION["m_cage"];

html of form, showing both select boxes and form submission button

<body>

    <table>

        <h2>New Breeding Cage</h2>

            <form method="POST" action="addbcage.php">

                <tr><td>From Cage:</td>
                <td><select name="Mcage" id="Mcage">
                  <!-- list all cages in a dropdown-->
                        <?php $selectcage="SELECT id, name FROM cages;";
                        $selectcresults=mysqli_query($mysqli,$selectcage);

                        while ($row = $selectcresults->fetch_assoc()) {
                          if ($row['name'] === $m_cage){
                            echo '<option selected value=" '.$row['id'].' ">'.$row['name'].'</option>';
                          } else {
                            echo '<option value=" '.$row['id'].' ">'.$row['name'].'</option>';
                           }
                        }
                        ?>
                  </select></td></tr>

                  <tr><td>Animal:</td><td>

                  <?php

                  // if the user has selected a cage, show which animals are available to move
                  if (!empty($m_cage)) {
                    ?>
                    <select name="Malemouse" size="5">

                          <?php
                          $selectMmouse="SELECT animal_new.id as anid
                          from animal_new left join cages on animal_new.cage=cages.id
                          where cages.name='$m_cage';";

                        $Mmouseresults=mysqli_query($mysqli,$selectMmouse);
                            while ($row = $Mmouseresults->fetch_assoc()) {
                              // convert the date to m-d-Y
                              $t = date("m-d-Y", strtotime($row['dob']));
                            echo '<option value=" '.$row['anid'].' ">'.$row['anid'].'</option>';}

                      ?>
                    </select></td></tr>
            </table>

                <input type="submit" name="submitcage" value="click to submit">
              </form>

    </body>
</html>
1

There are 1 answers

0
miken32 On

There are many things wrong with your code, primary among them that you are replacing the entire page's markup with something created by PHP instead of just replacing the select element. You're very vulnerable to SQL injections as well, and you should not be mixing HTML and PHP like you are. The HTML itself is a bit of a mess as well – an h2 and form element directly inside a table element? This should give you a start:

<?php
if (!empty($_POST)) {
    // deal with the POST request
} elseif (!empty($_GET["search_cage"])) {
    // this is coming from jQuery, we need to return a list of cages in JSON format
    // we're passed an ID, so search for it safely with prepared statements
    $stmt = $mysqli->prepare("SELECT id FROM animal_new WHERE cage = ?");
    $stmt->bind_param("i", $_GET["search_cage"]);
    $stmt->execute();
    $return = [];
    while ($row = $stmt->fetch_assoc()) {
        $return[] = $row["id"];
    }
    header("Content-Type: application/json");
    echo json_encode($return);
    die();
}

// this is to populate the first select element
$result = $mysqli->query("SELECT id, name FROM cages");
$cages = [];
while ($row = $result->fetch_assoc()) {
    $cages[] = $row;
}

?>
<!doctype html>
<html>
<head>
    <title>58862065</title>
    <script>
        $(document).ready(function() {
            $("#Mcage").change(function() {
                // we send an ID to ensure proper matching, not some text
                var id = this.value;
                var url = "addbcage.php";
                var data = {search_cage: id};
                $.get(url, data, function(json) {
                    // now we have a response from the server
                    var sel = $("#Malemouse");
                    //clear the existing options
                    sel.empty();
                    // now loop over the JSON array and create a new option for each item
                    $.each(json, function(i, d) { sel.append($("<option>").val(d).html(d)); });
                });
            });
        });
    </script>
</head>
<body>
    <h2>New Breeding Cage</h2>

    <form method="POST" action="addbcage.php">
        <table>
            <tr>
                <td>From Cage:</td>
                <td>
                    <select name="Mcage" id="Mcage">
                        <!-- list all cages in a dropdown -->
<?php foreach($cages as $cage): ?>
                        <option value="<?= $cage["id"] ?>"><?= $cage["name"] ?></option>
<?php endforeach ?>
                    </select>
                </td>
            </tr>

            <tr>
                <td>Animal:</td>
                <td>
                    <select name="Malemouse" id="Malemouse" size="5">
                        <!-- note this is empty to start with -->
                    </select>
                </td>
            </tr>
        </table>

        <button type="submit">click to submit</button>
    </form>

</body>
</html>

In a nutshell, the second select element is created empty. jQuery will send the database ID when the first select changes, and PHP responds with a simple JSON array. Then that array is used to build new option elements for the second select element. Obviously, I don't have any way to test this, you may come across some typos and bugs along the way. But it will get you going in the right direction.