-2

I wrote a script to filter though a database and select all the records that contain certain value. I have an AJAX dropdown to select the value. However when I make a selection in the dropdown it does not return any results. Any help would be appreciated. There are two code snippets the index.php is where the dropdown and table output are. Type.php does the database query and sends the results back to the index.php

Index.php

<html>
<head>
    <title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>
<body>
    <form>
    <?php

include ("includes/dbh.inc.php");

$type = "SELECT typeName FROM types";
$stmt = $mysqli->prepare($type);
$stmt ->execute();
$stmt ->bind_result($typeName);
$stmt ->store_result();
echo '<select onchange="showType(this.value)" name"showType">';
echo '<option>Select Car Type</option>';
while($stmt->fetch()){
    
echo '<option value="'.$typeName.'"">'.$typeName.'</option>';

}
echo '</select>';

$stmt ->close();
    <a href="index.php">Show All</a>
</form>



<table id="carList" border="1">
    <thead>
        <tr>
            <th>picture</th>
            <th width="500">Details</th>
        </tr>
    </thead>
<tbody>
    
</tbody>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
    $("#typeName").on("change", function() {
        $.ajax({
            type: "POST",
            data: {
                "typeName": $("#typeName").val()
            },
            url:"type.php",
            dataType: "json",
            success: function(JSONObject){
                var carHTML = "";

                for (var key in JSONObject){
                    if(JSONObject.hasOwnProperty(key)){
                        carHTML += "<tr>";
                        carHTML +="<td>" + JSONObject[key]["stockName"] + "</br>" 
                        carHTML += JSONObject[key]["stockPack"] + "</td>";
                        carHTML += "</tr>";
                    }
                }
                $("#carList tbody").html(carHTML);
            }
        });
    });
</script>

Type.php

<?php 
include_once 'includes/dbh.inc.php';


$sql = "SELECT * FROM rollingstock WHERE stockType=?";

$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
    echo "SQL statment failed";
} else {
    mysqli_stmt_bind_param($stmt, "s", $_POST["typeName"]);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $carArray = [];
        while ($row = mysqli_fetch_assoc($result)){
            array_push($carArray, [
        'stockName' => $row['stockName'],
        'stockPack' => $row['stockPack']
    ]);
        }

}

$JSONoutput = json_encode($carArray);
echo $JSONoutput;
 
David
  • 389
  • 5
  • 22
  • 4
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Nov 12 '20 at 22:57
  • 1
    Open the network tab in the debugger of your browser and paste here the output (or the error) for the requests. – Anarcociclista Nov 12 '20 at 23:13
  • Why are you including jQuery twice? – Phil Nov 12 '20 at 23:39
  • @Anarcociclista this comes back from the type.php [{"stockName":"Shoving Platform","stockPack":"Mixed Freight Pack 2"},{"stockName":"Shoving Platform","stockPack":"Mixed Freight Pack 2"}] there are no errors shown – David Nov 12 '20 at 23:57
  • @Phil that was an oversight – David Nov 12 '20 at 23:57
  • Add an error handler to your AJAX call, eg `error: function(_, status, error) { console.error(status, error) }`. Also, [don't use `for..in` to iterate an array](https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea) – Phil Nov 13 '20 at 00:01

1 Answers1

-1

Can you try parsing the JSONObject like so:

parsed_result = JSON.parse(JSONObject);
for (var key in parsed_result){
    if(parsed_result.hasOwnProperty(key)){
        carHTML += "<tr>";
        carHTML +="<td>" + parsed_result[key]["stockName"] + "</br>" 
        carHTML += parsed_result[key]["stockPack"] + "</td>";
        carHTML += "</tr>";
    }
}
$("#carList tbody").html(carHTML);

This should be in the comment section but i dont have the rep. Also please use prepared statements.

ACA
  • 3
  • 2