JQuery/PHP Dynamic Dropdown Issue

你说的曾经没有我的故事 提交于 2020-01-07 02:01:07

问题


I've been building a script for dynamic dropdowns using PHP and JQuery and I'm having an issue with some of the data being sent from the form to be queried. Basically the user will choose an option from the first box and from there ever other box is dependent on the previous. The options are pulled from a MySQL database and as these same options are being picked they are sent back to the script to create the next query and so on. I'm having issues with some of the data and I think it's because there are spaces in the options being sent through GET. I've looked over my script many times the past few days and I just can't find a solution.

Here is a live version of my script to test. - That's the url for a live version of the script to check out.

Here is the front-end. A pretty basic form and some javascript to send the information to the back-end script:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(function(){
                $("#series").change(function() {
                    $("#range").load("findbackend.php?series=" + $("#series").val());
                });
                $("#range").change(function() {
                    $("#digsize").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val());
                });
                $("#digsize").change(function() {
                    $("#dignum").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val() + "&digsize=" + $("#digsize").val());
                });             
              });
        </script>
    </head>
    <body>
        <select id="series">
            <option selected value="base">Please Select</option>
            <option value="FM800">FM800</option>
            <option value="F100">F100</option>
        </select>
        <br>
        <select id="range">
            <option>Please choose from above</option>
        </select>
        <br>
        <select id="digsize">
            <option>Please choose from above</option>
        </select>
        <br>
        <select id="dignum">
            <option>Please choose from above</option>
        </select>
    </body>
</html>

And here is the back-end I've come up up with:

<?php
    //\\ MODULAR DEPENDANT DROPDOWNS \\//

    //creates DB connection
    $dbHost = 'host';
    $dbUser = 'user'; 
    $dbPass = 'pass';
    $dbDatabase = 'database';
    $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());

    mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());

    //prevents injections
    $series = mysql_real_escape_string($_GET['series']);
    isset($_GET['range'])?$range = mysql_real_escape_string($_GET['range']):"";
    isset($_GET['digsize'])?$digsize = mysql_real_escape_string($_GET['digsize']):"";
    isset($_GET['dignum'])?$dignum = mysql_real_escape_string($_GET['dignum']):"";

    //forms the query depending on what data is recieved through GET    
    if (isset($_GET['dignum'])) {
        $query = "SELECT DISTINCT * FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' AND dig_num='$dignum' ORDER BY sio";
    } elseif (isset($_GET['digsize'])) {
        $query = "SELECT DISTINCT dig_num FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' ORDER BY sio";
    } elseif (isset($_GET['range'])) {
        $query = "SELECT DISTINCT dig_size FROM meters WHERE series='$series' AND sio='$range' ORDER BY sio";
    } else {
        $query = "SELECT DISTINCT sio FROM meters WHERE series='$series' ORDER BY sio";
    }

    //creates a result array from query results
    $result = mysql_query($query);

    //outputs dropdown options dependent on what GET variables are set
    if (isset($_GET['digsize'])) {
        while ($row = mysql_fetch_array($result)) {
        echo "<option value='" . $row{'dig_num'} . "'>" . $row{'dig_num'} . "</option>";
        }
    } elseif (isset($_GET['range'])) {
        while ($row = mysql_fetch_array($result)) {
        echo "<option value='" . $row{'dig_size'} . "'>" . $row{'dig_size'} . "</option>";
        }
    } else {
        while ($row = mysql_fetch_array($result)) {
        echo "<option value='" . $row{'sio'} . "'>" . $row{'sio'} . "</option>";
        }
    }
?>

Again, new.foxmeter.com/find.php is a live version of my script to check out.

This is a monospaced snippet of my table that I'm pulling data from: i.imgur.com/IOT9RUF.png

Thanks in advance for any help!


回答1:


Your instincts were right, the problem is with non-escaped characters (url encoding). For debugging AJAX calls you should use your browser's console (I highly recommend FireBug, but to each his own).

Before you send the parameters via AJAX, you have to encode them using encodeURI(). For example:

$("#series").change(function() {
    var val = document.getElementById('series').value;
    // $("#series").val() == document.getElementById('series').value
    // but the latter is faster!
    $("#range").load(encodeURI("findbackend.php?series=" + val));
});

You would also have to adjust your other .change function calls accordingly. Since the data your PHP script will receive has been encoded, you need to decode it using urldecode(). Example:

$series = mysql_real_escape_string(urldecode($_GET['series']));

This should work just fine.

On a side note, you are using a deprecated MySQL API, you should use MySQLi or PDO. Also, your jQuery calls could do with some caching (you create the $("#series") object three separate times).




回答2:


the easy way to use ajax so you need two php pages and one js at least
the first php will have the first dropdown and then send it`s value to the second php by ajax it's simply example

first php code like this

<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="dropdown.js"></script>
</head>
<body>
<select name="first" id="first">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<div id="second"></div>
</body>
</html>

dropdown2.php code is

<?php
if(isset($_GET['first'])){
  $first=$_GET['first'];
echo"
<select name='second' id='secondselect'>
<option value='4'>$first a</option>
<option value='5'>$first b</option>
<option value='6'>$first c</option>
</select>
";
}
?>

and dropdown.js

$(document).ready(function(){
$("#first").change(function(){
str=$("#first").val();
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","dropdown2.php?first="+str,false);
xmlhttp.send();
document.getElementById("second").innerHTML=xmlhttp.responseText;
});
});


来源:https://stackoverflow.com/questions/18873677/jquery-php-dynamic-dropdown-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!