简体   繁体   中英

Trying to get value from option on selected tag with jQuery and post to php page

I'm trying to get value from the selected option and post on a Php. But I also have a form to Post data as well. I'm trying to combine the two but now when I try to run the code I get a blank query page.

message.php

    <form  id="messageEmployeeForm" class="form table-striped" method="POST" action="core/query.php">

<select  id='toEmployee' class='form-control formBlock' name='toEmployee_id' value='' type='text' class='form-control formBlock'>
                     <option value="">To...</option>
                       <?php
        $employeesQuery = $db->query("SELECT * FROM employees");
        while ($employee = mysqli_fetch_assoc( $employeesQuery)) {
            ?>
      <option id='toEmployees_id' name='toEmployees_id' value="<?php echo $employee['employee_id'] ;?>">

     <?php echo $employee['first_name'] ;?> <?php echo $employee['last_name'] ;?></option>
     <?php } ;?>
    </select> 


//other inputs here...

        <input name="sendMessage" id="submit" type="submit" class="formBlock btn btn-success"  value="Send Message"/>
    </form>

jquery

<script>    

    $(document).ready(function () {
            $("#toEmployee").bind("change", function (e) {
                $.ajax({
                    type: "POST",
                    data: { data: $("#toEmployee").val() }
                });
            });
        });
</script>  

query.php

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sendMessage']) && isset($_POST['data'])){
$var = $_POST['data'];
//other data to be posted and bind here using prepared statements...

]

Your query.php file is expecting two post keys to be present during the request, without these it won't run the inner code.

isset($_POST['sendMessage']) && isset($_POST['data'])

Therefore inside your jQuery, you need to additionally send the sendMessage key like so:

$.ajax({
    type: "POST",
    data: { 
        data: $("#toEmployee").val(),
        sendMessage: 'your value'
    },
    success: function(data) {
        // do something with output (data)
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM