Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load JSON data with jQuery, PHP and MySQL

I want to create a dynamic dropdown menu that one select is based on the value of another select. I tried so many times and failed. I have the code as follows. Anyone can help me to find out what the problem is.

//template:

<script type="text/javascript">  

$(function(){ 
  getSelectVal(); 
  $("#grouptypes").change(function(){ 
      getSelectVal(); 

  }); 
});

function getSelectVal(){ 
    $.getJSON('<?php echo url_for('group_utilization/GroupModification') ?>', {'grouptypes':$("#grouptypes").val()},function(data){ 
        var groups = $("#groups"); 
        $("option",groups).remove(); 
        $.each(json,function(index,array){ 
            var option = "<option value='"+array['id']+"'>"+array['title']+"</option>"; 
            select.append(option); 
        }); 
    }); 
} 

</script>

GroupType: <select id="grouptypes">

  <?php foreach($grouptypes as $type) : ?>

  <?php echo "<option value='" . $type->name . "'>" .$type->name. "</option>"; ?>

  <?php endforeach ?>

</select><br />
<br />Result:<span id="list-of-groups"></span>

<br />
Group: <select name="group" id="groups">

</select><br />

Another file for returning database returned value:

if(isset($_GET["grouptypes"])){
 $grouptypes = $_GET["grouptypes"];

 $query = "SELECT g.name FROM groups g INNER JOIN group_types gt ON(gt.id = g.group_type_id AND gt.name = ?)";

 $groups = $db->getResultsForQuery($query, $grouptypes);
 echo json_encode($groups);
 }
like image 606
庆峰 扈 Avatar asked Feb 01 '12 21:02

庆峰 扈


1 Answers

Does your PHP Script sends the appropriate headers for JSON ?

try to put this juste before "echo json_encode($groups);". Eventually put an exit call to avoid extra output.

$groups = $db->getResultsForQuery($query, $grouptypes);
header('Content-type:application/json;charset=utf-8');
echo json_encode($groups);
exit();

like image 182
djleop Avatar answered Nov 18 '22 12:11

djleop