user1296114 user1296114 - 4 years ago 73
Javascript Question

Showing items with php and JSON dropdown

I got a sizing chart and I only want to show one result at the time next to the description of what that size means.

*Example i want to output B+C if id is 01, but thats using the CSV not the JSON file i made!..

How to make the php to show only the "ID": "01" items?

Then just show values from "name" and just from "2xs"

And thirdly with a dropdown choice another size and then it will show that.

enter image description here

So far i made my CSV to a JSon file.. but i dont understand how to output the data..

{
"ID": "01",
"name": "Height",
"2XS": 66,
"XS": 68,
"S": 70,
"M": 72,
"L": 74,
"XL": 76,
"2XL": 78,
"3XL": 80,
"4XL": 82,
"5XL": "",
"6XL": "",
"7XL": "",
"8XL": "",
"9XL": "",
"10XL": ""
}




This is how far I'm at on the php side :)

<?php
$json=file_get_contents("/sizes.json");
$result = json_decode(true);

print_r($result);
?>

Answer Source

No need for the PHP if the chart is in the same page as the HTML

I use jQuery here to give an example. Note I have made the object a little more complex to me more flexible

var items = { // could come from server directly as JSON
  "01": {
    "name": "Height",
    "sizes": [
      {"2XS": 66}, 
      {"XS": 68}, 
      {"S": 70},
      {"M": 72}, 
      {"L": 74}, 
      {"XL": 76}, 
      {"2XL": 78}, 
      {"3XL": 80}, 
      {"4XL": 82}, 
      {"5XL": ""}, 
      {"6XL": ""}, 
      {"7XL": ""}, 
      {"8XL": ""}, 
      {"9XL": ""}, 
      {"10XL": ""}
    ]
  },
  "02": {}
}
$(function() { // when page has loaded
  $("#chart").on("change", function() { // when first sel changes
    var $sizes = $("#sizes");
    $sizes.empty(); // clear the second sel
    var item = items[this.value], 
       sizes = item? item.sizes:[]; // if no item 
    $.each(sizes,function(_,size) { // each of the size array
      $.each(size,function(k,v) { // each option
       if (v) { // ignore empty
         $sizes.append($('<option>', {value:k, text:k+':'+v}));
       }  
      });
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="chart">
  <option value="">Please select</option>
  <option value="01">Dress</option>
</select>
<select id="sizes"></select>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download