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?

5
  • 1
    You know that your PHP and Javascript are running on different computers, right? Commented Jun 19, 2017 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 that will allow you to send val to a separate PHP page in that onchange function, which outputs just the <option>s that you can then dump into the #size element. Commented Jun 19, 2017 at 22:03
  • What is the supposed value of valSize in plain text? Commented Jun 19, 2017 at 22:04
  • Possible duplicate of How to pass variables and data from PHP to JavaScript? Commented Jun 19, 2017 at 22:10
  • Sidenote: Have you checked out appelsiini.net/projects/chained? Looks like you want to let a select change based on the value of another. chained does exactly that. Commented Jun 19, 2017 at 22:16

2 Answers 2

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);
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.

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.