How to load JSON data using jQuery, PHP and MySQL

I want to create a dynamic drop-down menu in which one selection will be based on the value of another selection. I tried many times and failed. I have the code as follows. Anyone can help me figure 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 to return the returned database:

 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); } 
+7
source share
4 answers

Does your PHP script send the appropriate headers for JSON?

try putting this juste before "echo json_encode ($ groups);" Finally, call exit to avoid extra output.

$ groups = $ db-> getResultsForQuery ($ query, $ grouptypes);
header ('Content-Type: application / JSON; encoding = UTF-8');
echo json_encode ($ groups);
Exit();

+1
source

In fact, the top block of code is:

 $(document).ready(function(){ getSelectVal(); $("#grouptypes").change(function(){ getSelectVal(); }); }); 
0
source

You need to associate the tag with jQuery var before adding:

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

You may have a problem with the url_for () function, since it will not be able to correctly output your link to use getJSON. For example, if I play with something close to your code (BTW, are you using Symphony?)

  $.post("<? echo 'server.php';?>", function(data) { aler(data); }); }); 

I get this link in my js code

 http://dev.wonderland/%3C?%20echo%20'server.php'?%3E 

which is obviously not the link I'm trying to get to. Also, be sure to add a semicolon at the end of your PHP code and try again.

0
source

All Articles