0

I already see data is loaded on Json/Ajax. I want to add data (value and description) in selected option. I did it this way. And all data is shown on one option tab. I am lost here. Below is the Ajax code and html.

$(function(){
      categoryload();
    });


  function categoryload() {
        //var hosname =window.location.protocol + "//" + window.location.hostname +  window.location.pathname;
        var hosname = window.location.protocol + "//" + window.location.hostname+ "/sgw/modules/controller/categorycontroller.php";
        alert (hosname);
        //var ur = hosname + "/modules/controller/categorycontroller.php";



        $.ajax({
          url:hosname , //the page containing php script
          type: "POST", //request type,
          dataType: 'json',
          data: '',
          success:function(data){
              alert(data);  
              var obj = data; 
              var areaOption = "<option value=''>Select Category </option>";
              for (var i = 0; i < obj.length; i++) {
                  areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
              }
              $("#category").html(areaOption);                          
            }
       });
   }

HTML

<div class="form-group">
        <label class="control-label col-md-4">Service Category:</label>
        <div class="col-md-7">
            <select class="form-control" name="category" id="category">
                    <option value="0">Select Category</option>
                    <option value="1"> </option>
                    <option value="2"> </option>            
            </select>
        </div>
        </div>

Categorycontroller.php

require '../service/categoryService.php';


$categoryname = @trim(stripslashes($_POST['category']));
$category = new  categoryService();
$list = array();
$list[]= $category->categorylist();

$return["json"] = json_encode($list);

echo $return["json"]; 
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Max
  • 61
  • 1
  • 9
  • Can you check if `obj.length` is always one even with multiple elements in the object? – user2464424 Feb 06 '18 at 18:17
  • Yeah. When I checked it, the obj length is only 1. :( . How to read array length ? Thank you. – Max Feb 07 '18 at 02:58
  • The `length` method can't be used for objects. It appears that all you need is to loop through an object entirely tho. [Check this.](https://stackoverflow.com/a/14379304/2464424) Else, use `Object.keys(fruits).length` to extract all the keys into a normal array and get the length. – user2464424 Feb 07 '18 at 08:14

0 Answers0