c_shelswell Posted September 6, 2009 Share Posted September 6, 2009 Ok so i've take up previous advice and tried to use json.encode with my data but now all I get returning to my select box is 'undefined'. I know i'm getting results from my mysql query it just my select box isn't populating with the data. my code is: foreach ($cats as $k => $v) { $arr["optionValue: ".$v['id'].""] = "optionDisplay: '".$v[DEFAULT_LANG]."'"; } echo "[".json_encode($arr,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP)."]"; Then the javascript on the page with the select box is: $(function() { $("select#membersOrPublic").change(function() { $.getJSON("get_categories.php",{id: $(this).val(), ajax: 'true'}, function(j) { var options = ''; for (var i = 0; i < j.length; i++) { options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'; if (j[i].optionValue == 0) { // no results have been returned } } $("select#categoryList").html(options); }) }) }) I'm afraid I'm not overly familiar with JSON so finding this one quite difficult to problem solve Cheers Quote Link to comment Share on other sites More sharing options...
corbin Posted September 6, 2009 Share Posted September 6, 2009 json_encode takes an associative array and JSON'izes it. In other words, look at the output of that script. You'll see that it's not JSON formatted. Also, [] is the syntax for an array and JSON is an object. (You don't need the [].) Quote Link to comment Share on other sites More sharing options...
c_shelswell Posted September 6, 2009 Author Share Posted September 6, 2009 Thanks for the reply. Thing is if i remove the [] I don't even get undefined I just don't get anything. I'm getting this: {"optionValue: 1":"optionDisplay: \u0027WELCOME GIFTS\u0027"} perhaps I'm formatting it wrong? Quote Link to comment Share on other sites More sharing options...
corbin Posted September 7, 2009 Share Posted September 7, 2009 Yes, that's formatted incorrectly. AJAX is basically just an object, and object notation is: {"key": "value", "key2": "value2"} So, you'll need to make it match that. Here's an example: echo json_encode(array( 'people' => array( array('name' => 'Corbin', 'hobby' => 'PHP'), array('name' => 'John', 'hobby' => 'Something else') ) )); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.