2

I know that using php inside js is a bad practice, but unfortunately for now my skill is not enough to come up with something else.

$(document).ready(function() {

        $("#type").change(function() {
            var val = $(this).val();

            valSize = "<?php $sql = "SELECT model FROM cars WHERE brand = 'val'";
                             $result = mysqli_query($conn, $sql);
                             while($row = mysqli_fetch_assoc($result)){
                                echo '<option>'.$row['model'].'</option>';
                             }
                       ?>";

            $("#size").html(valSize);

        });


    });

Is there any way how I could add val variable inside php code?

Nikita Ribakovs
  • 305
  • 3
  • 11
  • 1
    You know that your PHP and Javascript are running on different computers, right? –  Jun 19 '17 at 22:03
  • No, the PHP is executed on the server before your HTML and Javascript are sent to the browser. The JS `change` event is fired when your users change the `#type` element in the browser, so PHP's work is long done at that point. jQuery has [AJAX functions](http://api.jquery.com/category/ajax/) that will allow you to send `val` to a separate PHP page in that onchange function, which outputs just the ` – rickdenhaan Jun 19 '17 at 22:03
  • What is the supposed value of `valSize` in plain text? – SaidbakR Jun 19 '17 at 22:04
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – Jonathan Kuhn Jun 19 '17 at 22:10
  • Sidenote: Have you checked out https://appelsiini.net/projects/chained/? Looks like you want to let a select change based on the value of another. chained does exactly that. – Ruben Vincenten Jun 19 '17 at 22:16

2 Answers2

3

Your best bet would be to use a JavaScript AJAX call to send a request to another php file on your server.

First, create a separate PHP file on your server, I'll label it query.php (ONLY for the purposes of this explanation, I'd recommend choosing something more meaningful to your application).

<?php
if ($_POST['brand']) {
    // Be sure to set up your SQL $conn variable here
    $conn = ...;
    $sql = "SELECT model FROM cars WHERE brand = '" . $_POST['brand'] . "'";
    $result = mysqli_query($conn, $sql);
    $data = []; // Save the data into an arbitrary array.
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    echo json_encode($data); // This will encode the data into a variable that JavaScript can decode.
}

Then in your JavaScript, perform the AJAX request:

$(document).ready(function() {

    $("#type").change(function() {
        var val = $(this).val();

        $.post('query.php', {'brand' : val}, function(data){
            var jsonData = JSON.parse(data); // turn the data string into JSON
            var newHtml = ""; // Initialize the var outside of the .each function
            $.each(jsonData, function(item) {
                newHtml += "<option>" + item['model'] + "</option>";
            })
            $("#size").html(newHtml);
        });
    });
});
D. R.
  • 324
  • 1
  • 10
0

You can't execute the php code once the page has loaded. You're going to have to make a ajax call to a php file, that queries the data you need and echos that back to the original file. I would also recommend encoding it using echo json_encode($queryResults); Then you can JSON.parse($data);the return data in the success function of the ajax call.

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43