简体   繁体   中英

Jquery cascading dropdowns with php and catalyst

I am trying to implement cascading dropdown menus within a catalyst web app. The objective is to select a database table in the first menu and have the columns in that table appear in the second menu. My strategy is to use Jquery with a PHP helper script to run the query against the database.

Jquery code:

$("#db_table").change(function() {
    console.log("dbtable changed");
    $("#db_field").load("[% c.uri_for('/field_get.php')%]?choice=" + $("#db_table").val());
});

PHP:

<?php
    $username = "webuser";
    $password = "webuser";
    $hostname = "localhost";

    $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
    $selected = mysql_select_db("mousesom", $dbhandle) or die("Could not load database");
    $choice = mysql_real_escape_string($_GET['choice']);

    $query = "SELECT column_name FROM information_schema.columns WHERE table_name = '$choice';";

    $result = mysql_query($query);

    while ($row = mysql_fetch_array($result)) {
        echo "<option>" . $row{'dd_val'} . "</option>";
    }
?>

HTML:

Table:<select id="db_table">
   <option selected value="base">Choose a Table</option>
   <option value="neurons">Neurons</option>
   <option value="peaks_factors">Transcription Factors</option>
   <option value="peaks">Peaks</option>
   <option value="peaks_selection">Selection</option>
   <option value="peaks_histmods">Histone Modification</option>
</select>
Field:<select id="db_field">
   <option value="Placeholder">Please Select a Table</option>
</select>

I have thus far verified that the javascript request is firing, but I am not getting the expected response. Based on the log output from the Catalyst test server, it seems most likely the needed arguments are not being passed to the PHP helper script, instead being split off into query params by Catalyst instead...

[info] *** Request 8 (0.013/s) [17122] [Fri Jun 26 19:22:50 2015] ***
[debug] Path is "/"
[debug] Arguments are "field_get.php"
[debug] "GET" request for "field_get.php" from "10.21.136.40"
[debug] Query Parameters are:
.-------------------------------------+--------------------------------------.
| Parameter                           | Value                                |
+-------------------------------------+--------------------------------------+
| choice                              | peaks_histmods                       |
'-------------------------------------+--------------------------------------'

Clearly this is not what I want to happen and am wondering if Catalyst has another way of passing these params to the helper script or some other workaround. I've been searching various documentations and have, thus far, come up empty-handed. Any help would be appreciated!

Your request is being handled as if it's a Catalyst action because you're telling it to when you use the template code [% c.uri_for() %] . If you're going to call a PHP script, it needs to be outside the Catalyst URI namespace, perhaps by putting it amongst your root/static resources, or somewhere else your webserver expects to find PHP resources.

Having said that, I do not understand why you would introduce PHP into this mix. A Catalyst controller that returns the list of column names should be trivial to implement. The following untested code assumes you have a database handle available in your Catalyst app called $dbh . Whatever DB abstraction layer you're using (DBIC?), there's a straightforward way to get this. You might also choose to create proper model code for this.

sub get_fields :Args(1) {
    my ($self, $c, $table) = @_;
    my $qry = "SELECT column_name FROM information_schema.columns WHERE table_name = ?";
              # we'll have none of that nasty SQL injection-vulnerable code here...
    my $result = "";
    my @res = $dbh->selectall_arrayref($qry, { Slice=>{} }, $table );
    map { $result .= sprintf("<option>%s</option>", $_->{column_name} } @res;
    $c->res->body($result);
}

I will be the first to point out that this approach is not best-practice, but it might give you some ideas about how this should be done. (Hint: a better practice would be to return the column names as JSON, and handle creating <option> tags in jQuery, rather than creating a HTML snippet in your Catalyst Action. Because you might find a method that accepts a table name and returns its columns might be generically useful.)


Update

You can use Catalyst::View::JSON, and by putting your list of columns into $c->stash->{json} , it will Do The Right Thing, even if it is overkill for the use-case. You can also just convert to JSON and return it in $c->res->body() : if that is not empty, all template processing is bypassed. So what you need might be as simple as:

use JSON;

sub get_fields :Args(1) {
    my ($self, $c, $table) = @_;
    my @rows = $c->model('InformationSchema')->result_set('Columns')->search({table_name => $table});
    my $columnlist = [ map { $_->column_name } @rows ];
    $c->res->body(to_json($columnlist));
}

... but a bit more error-checking would be no bad thing.

Accessing from jQuery boils down to something like (again, untested):

$("#db_table").change(function() {
    $.ajax({
        type: "GET",
        url: "[% c.uri_for('/__your_module__/get_fields/') %]" + $("#db_table").val(),
        success: function(json){
            $.each(json, function(i, val) {
                $('#db_field').append($('<option>').text(val).attr('value', val));
            });
        }
    });
});

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