0

I have 2 selects, where the second one should be populated based on what is selected in the first one. But I can't fully get it to work.

If I use dataType: 'Json' in the call, it get a parser error, and if I remove I can get it to perform the empty part on the test select. So I must have some kind of parsing error, and I can't get it to append to the test select. How do I solve these issues?

The first one is created like this:

<select
    size="1"
    id="farvestandard"
    name="farvestandard" 
    class="listform ays-ignore" style="width: 155px;">
<?php
  $farveid = $res['r54'];
  $farvesql = "select * from farvekoder group by farvestandard";
  $farvequery = mysql_query("$farvesql") or die(mysql_error);

  while($farverow = mysql_fetch_array($farvequery, MYSQL_ASSOC)) {
      $select = '';
      if ($farverow['farvestandard'] == $res['farvestandard'])
          $select = ' selected';
      ?>
      <option
          value="<?php echo $farverow['farvestandard']; ?>"
          <?php echo $select; ?>>
              <?php echo $farverow['farvestandard']; ?>
      </option>
      <?php
  }
?>
</select>

and the second one, which should be populated depending on the selection in the first one.

<select name="test" id="test">
  <option value="">-- select one -- </option>
</select>

JQuery script

<script>
  $("#farvestandard").change(function() {
  var farvestandardID = $(this).val();

  if (farvestandardID) {

    $.ajax({
      url: "/farvekoderajax.php",
      dataType: 'Json',
      data: {
        'id': farvestandardID
      },
      success: function(data) {
        console.log("success");
        $('select[id="test"]').empty();
        $('select[id="test"]').append('<option value="">Vælg farvekode</option>');
        $.each(data, function(key, value) {

          $('select[id="test"]').append('<option value="' + key + '">' + value + '</option>');
        });
      },
      error: function(data, error) {
        console.log(arguments);
      }
    });
  }
});
</script>

and last the farvekoderajax.php page

<?php
    require('system/global_defs.php');
    $mysqli = new mysqli($MYSQL_DEFS["host"],$MYSQL_DEFS["user"],$MYSQL_DEFS["password"], $MYSQL_DEFS["db"]);
    echo $sql = "SELECT * FROM farvekoder WHERE farvestandard LIKE '%".$_GET['id']."%' AND inaktiv = 0 AND status = 3 ORDER BY farvekode ASC"; 
    $result = $mysqli->query($sql);
    $json = [];
    while($row = $result->fetch_assoc()){
            $json[$row['id']] = $row['farvekode'];
    }
    echo json_encode($json);
    return json_encode($json);
?>

If I open farvekoderajax.php with variable, I'll get this result:

{
  "3": "3009",
  "1": "7015",
  "34": "7021",
  "25": "7024",
  "4": "7035",
  "2": "7046"
}

Can't see what's wrong with that, and that is what it should populate test with.

If I remove datatype:json I get this below error :

TypeError: right-hand side of 'in' should be an object, got string

Stphane
  • 3,368
  • 5
  • 32
  • 47
  • Why the php has a return? just let the `echo json_encode($json)` – Roy Bogado Jul 02 '19 at 12:04
  • @roy The OP gets a parser error that way. Lars, what is returned via the ajax call which you are trying to parse as `JSON`? Please add that example data to your post. – Ryan Wilson Jul 02 '19 at 12:05
  • @RyanWilson Yep, sorry. For sure is a php problem, just remove the dataType and check if the php's json is correct with any online json validator – Roy Bogado Jul 02 '19 at 12:06
  • @Roy No worries, you are just trying to help. – Ryan Wilson Jul 02 '19 at 12:07
  • Well, the return json_encode() was just a try to see if that could fix anything. – Lars Sørensen Jul 02 '19 at 12:10
  • @LarsSørensen remove all script from `success` (and the `datatype`) and let just a `console.log(data)` to see whats really the php is returning. – Roy Bogado Jul 02 '19 at 12:26
  • You are echoing out your SQL: `echo $sql = "SELECT ...` - this would end up getting sent back and mess up the JSON. Remove the `echo`: `$sql = "SELECT ...` – MER Jul 02 '19 at 12:29
  • If I just keep console.log(data) in success I get this: {"3":"3009","1":"7015","34":"7021","25":"7024","4":"7035","2":"7046"} – Lars Sørensen Jul 02 '19 at 12:47
  • It's like it can't handle the strings, but why is that? – Lars Sørensen Jul 02 '19 at 13:32
  • Ahh, may have found out what is wrong. I need to parse to JSON in $.each also like $.each(JSON.parse(data), function(key, value) { $('select[id="test"]').append(''); }); That seems to work. – Lars Sørensen Jul 02 '19 at 14:12
  • Possible duplicate of [Can I mix MySQL APIs in PHP?](https://stackoverflow.com/questions/17498216/can-i-mix-mysql-apis-in-php) – Dharman Jul 02 '19 at 23:40
  • It seems to work with parsing the data in $.each. But I still have to remove datatype:json. – Lars Sørensen Jul 04 '19 at 12:43

1 Answers1

0

I had to parse the data as json like this

$.each(JSON.parse(data), function(key, value) {}

and also remove datatype:json before it worked.