php – Problem with $.getJSON in jquery – Education Career Blog

My Jquery code

function nalozi() {
  var id_skupine = $('#skupina option:selected').val();
  $('#artikel option').remove();

  //$('#artikel').append('<option value="'+id_skupine+'">'+id_skupine+'</option>');
  $.getJSON('artikli.php', {id_skupine:$('#skupina').val()}, function(data) {
    $.each(data, function(index,item) {
      $("#artikel").append("<option value=" + item.id + ">" + item.ime_artikla + "</option>"); 
    });
  });  
} 
$(document).ready(function() {
  nalozi();
  $('#skupina').change(function() {
    nalozi();
  });
});

AND PHP CODE

<?php

if(isset($_GET'id_skupine')) 
{
 $id_skupine = $_GET'id_skupine';
 $poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
 $velikost = mysql_num_rows($poizvedba);

 for ($i=0;$i<$velikost;$i++)
 {
        $elements=mysql_fetch_assoc($poizvedba);
 }

}
echo json_encode($elements);

?>

I don’t get the values back.

,

Update:

You should never put variable before sanitalizing/validating/type-converting into your sql queries. If your the value you expect in query string is a number, you need to properly type-cast it like this:

$id_skupine = (int) $_GET'id_skupine';

And if it is a string, the least you can do is to use mysql_real_escape_string function:

$str = mysql_real_escape_string($_GET'str');

Shouldn’t you be grabbing the records from db like this:

if(isset($_GET'id_skupine')) 
{
     $id_skupine = $_GET'id_skupine';
     $poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
     $velikost = mysql_num_rows($poizvedba);

     while($row = mysql_fetch_assoc($poizvedba)){
       $elements = $row'ime_artikla';
     }
}

echo json_encode($elements);

,

Might be your query is not returning anything

$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");

Remove single quote from '$id_skupine'

Try

$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '".$id_skupine."'");

Leave a Comment