Nikita Ribakovs
Nikita Ribakovs

Reputation: 315

Javascript inside PHP MYSQL query

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?

Upvotes: 2

Views: 7325

Answers (2)

D. R.
D. R.

Reputation: 334

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);
        });
    });
});

Upvotes: 3

Stephen Adkins
Stephen Adkins

Reputation: 100

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.

Upvotes: 0

Related Questions