mercredi 29 avril 2020

Having issues to get data from json file using ajax

I have 2 JSON files. One is for food types for e.g, Starters, Main Course, Beverages etc and the other is for displaying the details for each food item like the food name, food type, food description and price.

I want to select a food category from one JSON file and make an AJAX call to load another JSON file based on the first one in order to display the required food for that category. However, I am not getting the information.

<?php
  $url = 'http://localhost/trial2/buildFoodCategoriesJSON.php';
  $json = file_get_contents($url);
  $obj = json_decode($json, false);
?>

<p>Select a food category to view corresponding details
  <select id="foodCat">
    <option value=''></option>
    <?php foreach($obj as $foodCategory) {
      echo "<option value='" . $foodCategory->Food_Type . "'>". $foodCategory->Food_Type . "</option>";
    } ?>
  </select>
</p>
$(document).ready(function() {
  $('select#foodCat').change(function() {
    var fCategory = $(this).val();

    if (fCategory != '') { //if user did not choose blank
      var url = "http://localhost/trial2/getFoodItemsJSON.php?Food_Type=";
      url = url + fCategory;

      $.getJSON(url, function(data) {
        alert(JSON.stringify(data)); //no output
        $.each(data, function(i, obj) {
          foodName = obj['Food_Name'];
          foodDesc = obj['Food_Description'];
          foodPrice = obj['Food_Price(Rs)'];
          alert(foodName); //no output
        });
      });
    }
  });
});



Aucun commentaire:

Enregistrer un commentaire