简体   繁体   中英

Prepopulate input from previous SELECT option with PHP & SQL

I have a couple of SELECT that get Make & Models, I want to pre-populate a rating into an input box when the Model is chosen. This below is what I have, but it keeps giving me a page500 error each time I try something.

Not sure where I've gone wrong

this is from my class.php

public function ShowEfficRating() {
        include "db.php";
        $sql = "SELECT CONVERT(VARCHAR, Efficiency * 100) + '%' FROM Rating WHERE Model = $_POST[model]";
        $res = odbc_exec($cnn, $sql);
        $effic = $res
    }
    return $effic;

This is the jquery from my main page

<script>
    $(document).ready(function () {
        var model = $("select#model").val();
        $.post("selecttype.php", {model:model}, function(data) {
            return $('input[name="efficrating"]').val();
        });
    });
</script>

A few things:

  • Your return statement is outside your function.
  • Never pass $_POST data directly into a query. It must always be sanitized.
  • Passing unquoted string constant values directly into $_POST (eg $_POST[model] ) is deprecated. Use $_POST['model'] instead.

[edit to address using returned data:]

Take a look at the jQuery docs . They show that the data returned from the ajax request will be passed in to the callback function as the first parameter. Consider this modified version of your original ajax call:

<script>
    $(document).ready(function () {
        var model = $("select#model").val();
        $.post(
            "selecttype.php", 
            {model:model}, 
            function(data) {
                $('input[name="efficrating"]').val(data);
            }
        );
    });
</script>

It's now taking the data returned from the ajax call and using it to set the value of the input.

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