1

I want to make dynamic select options based on database values.

I am getting id when user select an option, I get this id in ajax and then this id is passed in PHP. In PHP I run SQL query based on provided id. Now I want to send response back in AJAX and then I will append my next select option with the given response.

This is my AJAX, from this code I am passing selected_val in PHP. `

    $(document).ready(function() {
        $(".sdpt").change(function(){ 
        let deptid = $(this).val();
        console.log(deptid);
        $.ajax({ 
            method: "POST",
            url: "joins.php",
            data: { selected_val: deptid }, 
            success: function(response){
                console.log(response);
        }
});
    });
});

`

In PHP, I am getting data (pro_name) from database and adding it in an array. I want to return this array in ajax and then I will use it there. Now it is return the whole PHP code in response. Please guide where I am doing mistake and what is the alternative.

`

if (isset($_POST['selected_val']) ) {
    $value = $_POST['selected_val'];
    $myq = new Database();
    $result = $myq->sql("SELECT * FROM programs where dept_id=$value");
    $arr = array();
    while($row = mysqli_fetch_assoc($result)){
        $arr[] = $row['pro_name'];
    };
    echo json_decode("Google");
}

`

  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Nov 23 '22 at 09:33
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Nov 23 '22 at 09:33
  • `Now it is return the whole PHP code in response`...this suggests that the PHP code is not being executed by the server. So presumably you're running this on a webserver which doesn't support PHP, or not on a webserver at all (e.g. via `file://`) – ADyson Nov 23 '22 at 09:34

0 Answers0