2

Not sure what I'm doing wrong here but I have the following AJAX function. console.log(make_id); is working fine, however data: {make:make_id}, doesn't seem to pass to /get_models.php - this line of code $make_id = $POST['make'];

$(document).ready(function() {
    $("#select_make").change(function() {
        var make_id = $(this).val();
        console.log(make_id);
        $.ajax({
            url: '/car_clearance_form/get_models.php',
            type: 'post',
            data: {
                make: make_id
            },
            dataType: 'json',
            success: function(response) {
                console.log(response);
                var len = response.length;
                $("#select_model").empty();
                for (var i = 0; i < len; i++) {
                    var model_id = response[i]['model_id'];
                    var model_name = response[i]['model_name'];
                    $("#select_model").append("<option value='" + model_id + "'>" + model_name + "</option>");
                }
            }
        });
    });
});

This is the code for get_models.php

I am getting the following error PHP Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given. $sql seems to be returning false, as $make_id isn't getting passed any thing from the AJAX function

<?php
   include "config.php";
   $make_id = $POST['make'];
   $sql = "SELECT model_name, model_id FROM models WHERE make_id = ".$make_id;
   $result = mysqli_query($con, $sql);
   $models_array = array();
   while ($row = mysqli_fetch_array($result) ) {
     $model_id = $row['model_id'];
     $model_name = $row['model_name'];
     $models_array = array("model_id" => $model_id, "model_name" => $model_name);
   }
   // encoding array to JSON format
   echo json_encode($models_array);
   ?>
ADyson
  • 57,178
  • 14
  • 51
  • 63
Ian Butler
  • 399
  • 7
  • 20
  • 9
    I think you've a `typo` at this line `$make_id = $POST['make'];` it should be `$_POST['make']` – A l w a y s S u n n y Dec 19 '17 at 15:58
  • 1
    [mysqli_query()](http://php.net/manual/en/mysqli.query.php) returned `FALSE`, which means that the selection query failed. As @BeingSunny pointed out, surely the problem stands in the typo – Brigo Dec 19 '17 at 16:00
  • @BeingSunny Thanks, that was it. There is another problem. `console.log(response);` is only returning the last item from `$models_array` – Ian Butler Dec 19 '17 at 16:03
  • @lan Butler because you are overwriting the value inside `while` loop – A l w a y s S u n n y Dec 19 '17 at 16:04
  • 1
    " only returning the last item from $models_array". No it's not. The problem is the $models_array only _contains_ the last item from the database results: `$models_array = array("model_id" => $model_id, "model_name" => $model_name);`. This over-writes the $models_array variable every time the loop runs. `$models_array[] = array("model_id" => $model_id, "model_name" => $model_name);` should do it – ADyson Dec 19 '17 at 16:04
  • 1
    do it like `$models_array[] = array("model_id" => $model_id, "model_name" => $model_name);` – A l w a y s S u n n y Dec 19 '17 at 16:05
  • 1
    P.S. 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 like this. – ADyson Dec 19 '17 at 16:06
  • 1
    Step 1: Learn how to debug AJAX calls so that you are not blind https://stackoverflow.com/questions/21533285/why-the-ajax-script-is-not-running-on-iis-7-5-win-2008-r2-server/21617685#21617685 – MonkeyZeus Dec 19 '17 at 16:09
  • Step 2: Using Step 1 make sure the parameters are going to your server – MonkeyZeus Dec 19 '17 at 16:11
  • Step 3: Does `echo $make_id;` produce the expected result – MonkeyZeus Dec 19 '17 at 16:11
  • Step 4: Not sure yet, how are steps 1-3 going? – MonkeyZeus Dec 19 '17 at 16:11
  • @MonkeyZeus Thanks for the link. I'm not blind anymore! – Ian Butler Dec 19 '17 at 16:21

2 Answers2

2

A couple of problems:

1) As BeingSunny pointed out, $POST['Make'] is a typo and should be $_POST['make']

2) As both BeingSunny and I pointed out, when you said your console.log is "...only returning the last item from $models_array", that's not actually true.

The real problem is that $models_array only contains the last item from the database results in the first place. The console.log is reporting exactly what it's given. The root cause of this is that $models_array = array("model_id" => $model_id, "model_name" => $model_name); over-writes the $models_array variable every time the loop runs.

$models_array[] = array("model_id" => $model_id, "model_name" => $model_name);

will fix that, as it will add a new entry to the array instead of completely obliterating the whole variable.

Also note my comments re your vulnerability to SQL injection attacks. Although this is not directly related to the question, it's certainly a problem you should address urgently.

ADyson
  • 57,178
  • 14
  • 51
  • 63
-4

Try putting "make" inside quotes so the code becomes:

$(document).ready(function() {
        $("#select_make").change(function() {
        var make_id = $(this).val();
        console.log(make_id);
        $.ajax({
            url: '/car_clearance_form/get_models.php',
            type: 'post',
            data: {'make':make_id},//here
            dataType: 'json',
            success:function(response) {
            console.log(response);
                var len = response.length;

                $("#select_model").empty();
                for(var i = 0; i<len; i++) {
                    var model_id = response[i]['model_id'];
                    var model_name = response[i]['model_name'];

                    $("#select_model").append("<option 
            value='"+model_id+"'>"+model_name+"</option>");
                }

            }

            });
            });
            });
m.kevin
  • 1
  • 2
  • 1
  • When declaring a JS object, the key does not need to be in quotes. You can easily test this using `var make = 'd'; console.log({make:1});` so this answer does not help. – MonkeyZeus Dec 19 '17 at 16:14