Home > Net >  How to use value of selected option to run query?
How to use value of selected option to run query?

Time:07-06

I'm fairly new to JavaScript and PHP so I have no idea what I'm doing for the most part. I'm making a Room Reservation System. What I want to do is get the selected option value from the 'room' select box so that I can use that value to run a query so that the time retrieved in the From and To select boxes has the available times for that specific room.

// To display all rooms in the database into the select box
    $select_query = "SELECT * FROM rooms";
    $result = $conn->query($select_query);
    if($result->num_rows > 0){
        $options = mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
    $today_date = date('Y-m-d');
    $disable_query = "SELECT room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '$today_date'";
    $start_from = 8;
    $end_from = 21;
    $start_to = $start_from 1;
    $end_to = $end_from 1;
    $disable = $conn->query($disable_query);
    $from_booked = [];
    $to_booked = [];
    if($disable->num_rows>0){
        while($row = $disable->fetch_assoc()){
            $from_booked_hour = date_parse($row['booking_start'])['hour'];
            $to_booked_hour = date_parse($row['booking_end'])['hour'];
            $from_booked = range($from_booked_hour, $to_booked_hour-1);
            $to_booked = range($from_booked_hour 1, $to_booked_hour);
        }
    }

This is my PHP code. I want to get the value of the selected room so that the query will include a room_id that is equal to the value of the selected room as well.

<label for="roomName" >Room</label>
<select required  name="room" id="room" onchange="selectbox(this.options[this.selectedIndex].value);">
    <option selected disabled value="">Select a room</option>
    <?php
        foreach($options as $option){
    ?>
    <option value=<?php echo $option['room_id'];?> ><?php echo $option['room_name']?></option>
    <?php
        }
    ?>
</select>
<div  style="padding: 0;">
    <div >
        <div >
            <label for="from" >From</label>
            <select required name="from" id="from" >
                <option selected disabled value="">Pick a time</option>
                <?php
                    for($hour = $start_from; $hour <= $end_from; $hour  ){
                        if(in_array($hour, $from_booked)){
                            if($hour < 10){
                                echo "<option disabled value = '0".$hour.":00:00'>".$hour.":00</option>";
                             }
                             else {
                                echo "<option disabled value = '".$hour.":00:00'>".$hour.":00</option>";
                             }
                                                        
                         }
                         else{
                             if($hour < 10){
                                 echo "<option value = '0".$hour.":00:00'>".$hour.":00</option>";
                             }
                             else {
                                 echo "<option value = '".$hour.":00:00'>".$hour.":00</option>";
                             }
                                                        
                         }
                     }
                 ?>
             </select>
             </div>
             <div >
                 <label for="to" >To</label>
                     <select required name="to" id="to" >
                        <option selected disabled value="">Pick a time</option>
                        <?php
                            for($hour = $start_from 1; $hour <= $end_from 1; $hour  ){
                                if(in_array($hour, $to_booked)){
                                    if($hour < 10){
                                        echo "<option disabled value = '0".$hour.":00:00'>".$hour.":00</option>";
                                    }
                                    else {
                                        echo "<option disabled value = '".$hour.":00:00'>".$hour.":00</option>";
                                    }
                                                        
                                }
                                else{
                                    if($hour < 10){
                                         echo "<option value = '0".$hour.":00:00'>".$hour.":00</option>";
                                     }
                                     else {
                                         echo "<option value = '".$hour.":00:00'>".$hour.":00</option>";
                                     }
                                                        
                                 }
                             }
                         ?>
                     </select>
                 </div>
             </div>
         </div>

I've tried AJAX and XMLHttpRequest to send the value from JavaScript to PHP but it's but both methods are not working. This is all in 1 php file by the way. I'm not sure if I'm doing anything wrong or if there is a simpler way to achieve what I want to achieve.

In my js file, I had the code for my last attempt at using AJAX to send the variable to PHP

function selectbox(val){
    $.ajax({
        url: 'home.php',    
        type: 'POST',    
        data: {    
            'value': val    
        },

        success: function(data){
            alert(data);
        }
    });
}

In my PHP, I had code that verify that it received the variable but it didn't work

if(isset($_POST['value'])){
    $room_id = $_POST['value'];
    echo "<script>alert('$room_id')</script>";
}

CodePudding user response:

You are missing the quotes in the selected option value. There is a short way to get the select value with jquery or raw js.

With jQuery you can use onchange="$(this).val()"

With Raw JS you can use onchange="this.value"

Both will return the selected value. Run the below code and check the console network you will see the value=test 1 or any selected value.

And in your PHP just print the value like below.

<?php 
    print_r($_POST);
    if(isset($_POST['value'])){ 
        echo $_POST['value'];
    }
?>

function sendAjax(val){
  alert(val);
  console.log(val);
  $.ajax({
    url:'home.php',
    method:"POST",
    data:{'value':val},
    success:function(data){
      console.log(data);
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select required  name="room" id="room" onchange="sendAjax(this.value);">
    <option selected disabled value="">Select a room</option>
    <option value="Test 1">Test 1</option>
    <option value="Test 2">Test 2</option>
    <option value="Test 3">Test 3</option>
    <option value="Test 4">Test 4</option>
    <option value="Test 5">Test 5</option>
</select>

CodePudding user response:

In web development things can be achieved in different ways. You're on the right path but you're missing some understanding of how everything sticks together.

PHP runs on the server, produces HTML code that gets sent to the browser. Browser runs html and js code.

Learn a bit more about PHP, GET, POST, and forms in general.

Then learn a bit JavaScript to get form data and how to use Ajax.

Then try to solve each problem individually: Example: First fix retrieving selected value with JavaScript and alert it to the browser before even worrying about sending it to PHP.

Then think of how you want your user experience to be. Is it a search form or booking form? Cause if it is search you could change form method to "get", either you might want to use "post".

Finally you could choose a solution to your problem.

A) When user selects room, reload the page with the room_id in the URL.

  • On room select box, listen to change event, for example with onchange attribute, and call js function that will retrieve the selected value
  • From that function, redirect with JavaScript to the URL of your script and adding the room id as query parameter, would end up something like: index.php?room_id=123
  • Finally, now the page reloads, and in your PHP code you can check if room_id parameter has been set in the $_GET array, and if has been, then you can add it to your SQL query (Btw also read about SQL injection and escaping params with php/mysql to keep your app safe)

B) When the user selects room, make an Ajax call to get values based on room

Say you don't want your whole page reload, you'd do something like:

  • Say you have your main form on index.php
  • You have your room select as usual
  • And you have another select that depends on room
  • Well this second select you have to leave it blank, without options
  • Then you create a JavaScript function called say: loadFromOptions()
  • Inside it you simply add some options to your select box, from JavaScript (google that)
  • Now you can open Chrome's developer tools, the Console tab, and run that function by writing it inside the console
  • Now you should see your "from" select being populated with some dummy options that you added
  • Now, you have to add the loadFromOptions() function to be called both on the onchange attribute of room select, but also on page load, because otherwise if your form has a default room selected, no options will be displayed unless changing room
  • Finally, to make the data real, modify your loadFromOptions() function
  • From inside it, get the selected value of your rooms select, and for now just alert it or console.log it
  • You can locate your rooms select by its id, and then get its value
  • Now create a new php file named say, from_dropdown_options.php
  • In that php file, you only add logic that will get the room parameter and query the database and spit a list of Option tags
  • Say when you open from_dropdown_options.php?room_id=123 in your browser, and you view page source, you should only see option tags
  • Finally, from your js function, make an Ajax Get request to your dropdown options php passing the room_id retrieved from the select and then assign the Ajax response to the "from" select content by using innerHTML property, ej: roomSelect.innerHTML=ajaxResponse;
  • Also a more robust way to do it, if you want to look into it is to use JSON, and respond from your php with JSON data, then loop it from your Ajax Json response, and create an option for each item
  • (One way you spit raw html options and stick them to the select, the other way you respond with a structured js data list and you use that data to generate the options with js)

Sorry I haven't posted almost any code examples but the internet is full of them, you just need to understand in what order to stick your pieces.

  • Related