0

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!

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I'll give this a shot and get back once I (hopefully) get it working.
Thanks for the other info, too. I do know about MySQLi but since I've learned the deprecated way I figured I'd it to get the script functioning then look into MySQLi and update it a bit later. As for the JQuery calls I'll have to look into that! I'm still new to PHP and even more so with javascript.
This was it! It worked on first refresh, too. One of the few times that has happened to me. Hah! Thanks to you I can honestly say I've learned something today (and also hopefully impress my boss).
0

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;
});
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.