如何生成动态下拉列表PHP Javascript mySQL [英] How to generate dynamic dropdown PHP Javascript mySQL

查看:86
本文介绍了如何生成动态下拉列表PHP Javascript mySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用PHP,Javascript和mySQL生成动态下拉列表时,我需要帮助.我对AJAX和Java语言不好,因此在这里寻求帮助.

I need help with generating dynamic dropdowns using PHP, Javascript and mySQL. I am not good with AJAX and Javascript and hence I'm asking for help here.

我有一个名为Hotel的表,其中包含酒店名称和类别的列表.它们按北,南,东和西等位置分类.我试图让用户选择他们想要的类别,然后第二个下拉列表将生成该特定类别下的可用酒店列表.如前所述,我对AJAX或JS不太满意.

I have a table named Hotel, which contains a list of hotel names and categories. They are categorised by locations such as North, South, East and West. I am trying to allow the user to pick the categories they want, then the second dropdown will generate a list of available hotels under that particular category. As mentioned, I am not good with AJAX or JS.

问题已解决!假设基本用户为root且没有密码,我已经编辑了使用数据库的答案.餐桌酒店有3列,分别是ID,类别和名称.

The question has been solved! I have edited my answer to work with the database, assuming basic user root and no password. the table hotel has 3 columns, id, category and name.

booking.php

<div class="form-group">
<label class="control-label col-sm-3" for="PreferredHotel">Preferred Hotel:</label>
<div class="col-sm-3">
<select class="form-control" name="hotelCategory" onchange="fetchHotelNameByArea(this.value)">
<option value="0">Please select area above first</option>
<?php
mysqli_select_db($dbConn, $database_dbConn);
$query_hotelselect = "SELECT * FROM hotel GROUP BY Category";
$hotelselect = mysqli_query($dbConn, $query_hotelselect) or die(mysqli_error($dbConn));
$row_hotelselect = mysqli_fetch_assoc($hotelselect);
while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
echo "<option value='" . $row_hotelselect['Category'] . "'> " . $row_hotelselect['Category'] . " </option>";
}
?>
</select>
<?php 
echo $row_hotelselect;
?>
</div>
<div class="col-sm-3" id="fetchHotelNameByAreaResult">
<select class="form-control">
<option value="0">Please select area above first</option>
</select>
</div>
<script>
function fetchHotelNameByArea(HotelArea) {
//above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
var xhttp = new XMLHttpRequest();
var url = "getter.php";//<- just a sample url
var data = new FormData();
//below will "assign HotelArea to $_POST['SearchValue']"
data.append('SearchValue', HotelArea);
xhttp.open('POST', url, true);
xhttp.send(data);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
}
}
}
</script>
</div>

getter.php

<?php
if ($_POST['SearchValue']) {
$searchname = $_POST['SearchValue'];
require_once('Connections/dbConn.php');

mysqli_select_db($dbConn, $database_dbConn);
$query_preferredhotel = "SELECT * FROM hotel WHERE Category = '$searchname'";
$preferredhotel = mysqli_query($dbConn, $query_preferredhotel) or die("Could not select examples");
$row_preferredhotel = mysqli_fetch_assoc($preferredhotel);
echo'<select class="form-control" name="preferredHotel">';
    while ($row_preferredhotel = mysqli_fetch_assoc($preferredhotel)) {
        echo "<option value='" . $row_preferredhotel['Name'] . "'> " . $row_preferredhotel['Name'] . " </option>";
    }
}echo '</select>';
?>

出现下拉列表后,金田陷入了困境.我在 https://css-tricks.com/dynamic-dropdowns/上找到了一篇文章,但是他们没有数据库的示例,我希望有人可以帮助我解决这个问题,因为据我了解,我很可能需要AJAX从数据库/服务器请求数据并填充第二个下拉列表.我没有要求 spoonfeeding ,但是我对AJAX的了解很少.任何指导都会有所帮助!

Kinda got stuck here after making the dropdown list appear. I found an article on https://css-tricks.com/dynamic-dropdowns/ but they do not have the example for the database and I was hoping someone could help me with this as I understand I would most likely need AJAX to request for data from the database/server and populate the second dropdown. Im not asking for spoonfeeding, but I really have very little clues about AJAX. Any guidance would be helpful!

已编辑

仅通过部分关键字传递的问题已解决,这要归功于Mark Ng发现我的标记错误!非常感谢您在回答我的问题方面所提供的所有帮助,谢谢!

The issue with only part of the keywords being passed has been solved, thanks to Mark Ng spotting my markup error! I am really thankful for all your help in answering my questions, thank you!

推荐答案

示例概念. 有2个select(下拉),第一个将根据其类别填充第二个.

sample concept. There are 2 select(dropdown), the first will populate the second based on its category.

第一次选择

<select onchange="fetchHotelNameByArea(this.value)">
    <option value="North">North</option>
    <option value="South">South</option>
    <option value="East">East</option>
    <option value="West">West</option>  
</select>   

第二次选择(稍后由javascript填充)

2nd select(to be populated by javascript later)

<div id="fetchHotelNameByAreaResult">
<!--For temporary only, this select was purposely placed inside this div id, it will get re-written by javascript when result are generated-->
<select>
    <option value="0">Please select area above first</option>
</select>
</div>

JS(本机)

<script>
function fetchHotelNameByArea(HotelArea) {
    //above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
    var xhttp = new XMLHttpRequest();
    var url = "./php/find_hotel_name_by_area.php";//<- just a sample url
    var data = new FormData();
    //below will "assign HotelArea to $_POST['SearchValue']"
    data.append('SearchValue',HotelArea);
    xhttp.open('POST',url,true);
    xhttp.send(data);
    xhttp.onreadystatechange = function() { 
        if(xhttp.readyState == 4 && xhttp.status == 200) {  
            document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
        }       
    }   
}
</script>

php查询(选择将通过javascript返回到div id ="fetchHotelNameByAreaResult"

php query (The select will be returned to div id="fetchHotelNameByAreaResult" by javascript

<?php
if($_POST['SearchValue']) {
    $searchname = $_POST['SearchValue']
    //.... your query
    //"SELECT * FROM hotel WHERE Category = '$searchname'";
    echo '<select class="blablabla">';
    while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
        echo "<option value=" . $row_hotelselect['id'] . "> " . $row_hotelselect['Name'] . " </option>";
        }
    }   
    echo '</select>';
    ?>      

这是怎么回事? 1.在第一个选择上,将触发onchange,调用函数fetchHotel ... 2. JS将数据发送到服务器,其中php文件将处理请求,onreadystate ...将检测响应是否准备就绪,innerHTML将用php生成的resposeText重写div id ="fetchHotelNameByAreaResult"中的内容脚本.

What is going on? 1. Upon 1st select, the onchange gets fired, calling function fetchHotel... 2. JS send data to server, where a php file will process the request, onreadystate... will detect if response is ready, and innerHTML will re-write whatever is in div id="fetchHotelNameByAreaResult" with the resposeText generated by the php script.

还有其他通过jQuery等实现此目的的方法.但是,一旦掌握了基本概念,就可以继续前进了.

There are other ways to do it via jQuery, etc. But once you get the basic concept, you are ready to move on.

编辑以解决此问题.

再一次,上面的代码工作正常.但是,我意识到 下拉列表仅将值的一部分传递给 变量(例如,丽兹卡尔顿,仅将丽兹传递给下一个表格).任何人 知道有什么解决办法吗?

Hey there again, the codes above works fine. But however, I realised that the dropdown list only passes one part of the value inside the variable (eg. ritz carlton, only passes ritz to the next form). Anyone aware of any solutions?

存在html标记错误.

There is a html markup error.

echo "<option value=" . $var . ">" . $var . "</option>";
//The above will return <option value=ritz carlton>ritz carlton</option> in html.
//the problem lies with value=ritz carlton as there is a space in between.
//html will think that it is value="ritz" while carlton is not a valid attribute, it will simply ignore it and only set the value as ritz, so only the value ritz was posted.

//In order to get the full string parse, you have to quote them like below.
echo "<option value='". $var ."'>" . $var . "</option>"; 
// echo "<option value=" . "'" . $var . "'" . "</option>";
// echo "<option value=/" " . $var . " /"</option>";
//a lot more ways to achieve same result.
//These will return <option value="ritz carlton">ritz carlton</option> in html. This will set the value as ritz carlton and the value "ritz carlton" will be posted.
?>

这篇关于如何生成动态下拉列表PHP Javascript mySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆